'use strict';

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

    const desc = await queryInterface.describeTable(table);
    if (!desc.final_inspection_number) {
      await queryInterface.addColumn(table, 'final_inspection_number', {
        type: Sequelize.STRING(60),
        allowNull: true
      });
    }

    const indexes = await queryInterface.showIndex(table);
    const hasUnique = indexes.some((idx) => idx.name === 'uniq_pfi_final_inspection_number');
    if (!hasUnique) {
      await queryInterface.addIndex(table, ['final_inspection_number'], {
        name: 'uniq_pfi_final_inspection_number',
        unique: true
      });
    }
  },

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

    try {
      await queryInterface.removeIndex(table, 'uniq_pfi_final_inspection_number');
    } catch (e) {
      // ignore if missing
    }

    const desc = await queryInterface.describeTable(table);
    if (desc.final_inspection_number) {
      await queryInterface.removeColumn(table, 'final_inspection_number');
    }
  }
};
