/**
 * Allow multiple Form 16A submissions with the same certificate number.
 * Duplicate submission is only when a credit note already exists for that dealer/quarter/amount
 * (enforced in run26asMatchAndCreditNote). Same certificate number without an existing
 * credit note (e.g. resubmission after 26AS upload) is allowed.
 */

import { QueryInterface } from 'sequelize';

export async function up(queryInterface: QueryInterface): Promise<void> {
  const sequelize = queryInterface.sequelize;
  // Drop unique constraint (PostgreSQL names it tablename_columnname_key when created via CREATE TABLE)
  await sequelize.query(
    `ALTER TABLE form16a_submissions DROP CONSTRAINT IF EXISTS form16a_submissions_form16a_number_key;`
  );
  // If a unique index exists on form16a_number (e.g. from Sequelize), drop it
  const [indexRows] = (await sequelize.query(
    `SELECT indexname FROM pg_indexes WHERE tablename = 'form16a_submissions' AND indexdef LIKE '%form16a_number%' AND indexdef LIKE '%UNIQUE%';`
  )) as [{ indexname: string }[], unknown];
  for (const row of indexRows || []) {
    if (row?.indexname) {
      await sequelize.query(`DROP INDEX IF EXISTS "${row.indexname}";`);
    }
  }
}

export async function down(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.addConstraint('form16a_submissions', {
    fields: ['form16a_number'],
    type: 'unique',
    name: 'form16a_submissions_form16a_number_key',
  });
}
