import type { QueryInterface } from 'sequelize';
import { DataTypes, QueryTypes } from 'sequelize';

module.exports = {
  up: async (queryInterface: QueryInterface) => {
    // Use information_schema so this migration is safe even if a previous run
    // recorded as "executed" but didn't actually alter the schema.
    const sequelize = (queryInterface as any).sequelize;

    const [colRow] = await sequelize.query(
      `SELECT CASE WHEN COUNT(*) > 0 THEN true ELSE false END AS exists
       FROM information_schema.columns
       WHERE table_name = 'tds_26as_entries' AND column_name = 'pan_number'`,
      { type: QueryTypes.SELECT }
    );

    if (!colRow?.exists) {
      await queryInterface.addColumn('tds_26as_entries', 'pan_number', {
        type: DataTypes.STRING(20),
        allowNull: true,
        comment: 'PAN from 26AS header (assessee PAN)',
      });
    }

    const [idxRow] = await sequelize.query(
      `SELECT CASE WHEN COUNT(*) > 0 THEN true ELSE false END AS exists
       FROM pg_indexes
       WHERE schemaname = 'public'
         AND tablename = 'tds_26as_entries'
         AND indexname = 'idx_tds_26as_pan'`,
      { type: QueryTypes.SELECT }
    );

    if (!idxRow?.exists) {
      await queryInterface.addIndex('tds_26as_entries', ['pan_number'], { name: 'idx_tds_26as_pan' });
    }
  },

  down: async (queryInterface: QueryInterface) => {
    // Best-effort rollback. If column/index already absent, these may throw.
    // We intentionally keep down strict because rollback isn't required for forward fixes.
    await queryInterface.removeIndex('tds_26as_entries', 'idx_tds_26as_pan');
    await queryInterface.removeColumn('tds_26as_entries', 'pan_number');
  },
};

