'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const table = 'production_fg_inward';
    const tables = await queryInterface.showAllTables();
    if (!tables.includes(table)) return;

    const desc = await queryInterface.describeTable(table);

    if (!desc.reference_fg_inward_id) {
      await queryInterface.addColumn(table, 'reference_fg_inward_id', {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: { model: 'production_fg_inward', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
        after: 'packing_id'
      });
    }

    if (!desc.balance_inward_qty) {
      await queryInterface.addColumn(table, 'balance_inward_qty', {
        type: Sequelize.DECIMAL(18, 3),
        allowNull: false,
        defaultValue: 0,
        after: 'inward_entry_qty'
      });
    }

    if (!desc.status) {
      await queryInterface.addColumn(table, 'status', {
        type: Sequelize.ENUM('PARTIAL_RECEIVED', 'FULLY_RECEIVED'),
        allowNull: false,
        defaultValue: 'PARTIAL_RECEIVED',
        after: 'inward_entry_date'
      });
    }

    try { await queryInterface.addIndex(table, ['reference_fg_inward_id'], { name: 'idx_pfgi_reference_fg_inward_id' }); } catch (e) { /* ignore */ }
    try { await queryInterface.addIndex(table, ['status'], { name: 'idx_pfgi_status' }); } catch (e) { /* ignore */ }
  },

  async down(queryInterface) {
    const table = 'production_fg_inward';
    const tables = await queryInterface.showAllTables();
    if (!tables.includes(table)) return;

    try { await queryInterface.removeIndex(table, 'idx_pfgi_status'); } catch (e) { /* ignore */ }
    try { await queryInterface.removeIndex(table, 'idx_pfgi_reference_fg_inward_id'); } catch (e) { /* ignore */ }

    const desc = await queryInterface.describeTable(table);
    if (desc.status) await queryInterface.removeColumn(table, 'status');
    if (desc.balance_inward_qty) await queryInterface.removeColumn(table, 'balance_inward_qty');
    if (desc.reference_fg_inward_id) await queryInterface.removeColumn(table, 'reference_fg_inward_id');
  }
};
