'use strict';

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

    const desc = await queryInterface.describeTable(table);

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

    // Drop unique index on route_card_id if present (created by table-level unique definition)
    try { await queryInterface.removeIndex(table, 'production_packing_route_card_id_unique'); } catch (e) { /* ignore */ }
    try { await queryInterface.removeIndex(table, 'route_card_id'); } catch (e) { /* ignore */ }

    try {
      await queryInterface.addIndex(table, ['route_card_id'], { name: 'idx_pp_route_card_id' });
    } catch (e) {
      // ignore duplicate index creation
    }
    try {
      await queryInterface.addIndex(table, ['reference_packing_id'], { name: 'idx_pp_reference_packing_id' });
    } catch (e) {
      // ignore duplicate index creation
    }

    // Extend enum to include PARTIAL_COMPLETED
    await queryInterface.sequelize.query(
      "ALTER TABLE production_packing MODIFY COLUMN status ENUM('PENDING','IN_PROGRESS','PARTIAL_COMPLETED','COMPLETED') NOT NULL DEFAULT 'PENDING';"
    );
  },

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

    try { await queryInterface.removeIndex(table, 'idx_pp_reference_packing_id'); } catch (e) { /* ignore */ }
    if ((await queryInterface.describeTable(table)).reference_packing_id) {
      await queryInterface.removeColumn(table, 'reference_packing_id');
    }

    try { await queryInterface.removeIndex(table, 'idx_pp_route_card_id'); } catch (e) { /* ignore */ }
    try { await queryInterface.addIndex(table, ['route_card_id'], { unique: true, name: 'uniq_pp_route_card_id' }); } catch (e) { /* ignore */ }

    await queryInterface.sequelize.query(
      "ALTER TABLE production_packing MODIFY COLUMN status ENUM('PENDING','IN_PROGRESS','COMPLETED') NOT NULL DEFAULT 'PENDING';"
    );
  }
};

