'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const table = await queryInterface.describeTable('fg_dispatch');

    const addIfMissing = async (name, definition) => {
      if (!table[name]) {
        await queryInterface.addColumn('fg_dispatch', name, definition);
      }
    };

    await addIfMissing('transporter_name', { type: Sequelize.STRING(150), allowNull: true });
    await addIfMissing('vehicle_no', { type: Sequelize.STRING(50), allowNull: true });
    await addIfMissing('driver_name', { type: Sequelize.STRING(120), allowNull: true });

    await addIfMissing('submitted_at', { type: Sequelize.DATE, allowNull: true });
    await addIfMissing('submitted_by', {
      type: Sequelize.INTEGER,
      allowNull: true,
      references: { model: 'User', key: 'id' },
      onUpdate: 'CASCADE',
      onDelete: 'SET NULL'
    });
    await addIfMissing('approved_at', { type: Sequelize.DATE, allowNull: true });
    await addIfMissing('approved_by', {
      type: Sequelize.INTEGER,
      allowNull: true,
      references: { model: 'User', key: 'id' },
      onUpdate: 'CASCADE',
      onDelete: 'SET NULL'
    });
    await addIfMissing('transit_started_at', { type: Sequelize.DATE, allowNull: true });
    await addIfMissing('transit_started_by', {
      type: Sequelize.INTEGER,
      allowNull: true,
      references: { model: 'User', key: 'id' },
      onUpdate: 'CASCADE',
      onDelete: 'SET NULL'
    });

    await queryInterface.changeColumn('fg_dispatch', 'status', {
      type: Sequelize.ENUM('PENDING', 'IN_TRANSIT', 'COMPLETED', 'CANCELLED'),
      allowNull: false,
      defaultValue: 'PENDING'
    });
  },

  async down(queryInterface, Sequelize) {
    const table = await queryInterface.describeTable('fg_dispatch');
    const removeIfPresent = async (name) => {
      if (table[name]) {
        await queryInterface.removeColumn('fg_dispatch', name);
      }
    };

    await removeIfPresent('transit_started_by');
    await removeIfPresent('transit_started_at');
    await removeIfPresent('approved_by');
    await removeIfPresent('approved_at');
    await removeIfPresent('submitted_by');
    await removeIfPresent('submitted_at');
    await removeIfPresent('driver_name');
    await removeIfPresent('vehicle_no');
    await removeIfPresent('transporter_name');

    await queryInterface.changeColumn('fg_dispatch', 'status', {
      type: Sequelize.ENUM('PENDING', 'COMPLETED', 'CANCELLED'),
      allowNull: false,
      defaultValue: 'COMPLETED'
    });
  }
};

