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

/**
 * Add explicit CSV-column fields to both SAP response tables.
 * Previously everything was dumped into raw_row; now each well-known SAP CSV column
 * has its own DB column, and raw_row holds only unexpected/extra columns.
 *
 * New columns (both tables):
 *   trns_uniq_no   – TRNS_UNIQ_NO from SAP response (our unique ID echoed back)
 *   tds_trns_id    – TDS_TRNS_ID from SAP response (= credit note number we sent)
 *   doc_date       – DOC_DATE  (SAP document date)
 *   tds_amt        – TDS_AMT   (amount confirmed by SAP)
 */
module.exports = {
  up: async (queryInterface: QueryInterface) => {
    const commonColumns = [
      ['trns_uniq_no', { type: DataTypes.STRING(200), allowNull: true }],
      ['tds_trns_id',  { type: DataTypes.STRING(200), allowNull: true }],
      ['doc_date',     { type: DataTypes.STRING(20),  allowNull: true }],
      ['tds_amt',      { type: DataTypes.STRING(50),  allowNull: true }],
    ] as const;

    for (const [col, def] of commonColumns) {
      await queryInterface.addColumn('form16_sap_responses', col, def).catch(() => {/* already exists */});
      await queryInterface.addColumn('form16_debit_note_sap_responses', col, def).catch(() => {/* already exists */});
    }

    await queryInterface.addIndex('form16_sap_responses', ['trns_uniq_no'], { name: 'idx_f16_sap_resp_trns_uniq_no' }).catch(() => {});
    await queryInterface.addIndex('form16_sap_responses', ['tds_trns_id'],  { name: 'idx_f16_sap_resp_tds_trns_id' }).catch(() => {});
    await queryInterface.addIndex('form16_debit_note_sap_responses', ['trns_uniq_no'], { name: 'idx_f16_dbt_sap_trns_uniq_no' }).catch(() => {});
    await queryInterface.addIndex('form16_debit_note_sap_responses', ['tds_trns_id'],  { name: 'idx_f16_dbt_sap_tds_trns_id' }).catch(() => {});
  },

  down: async (queryInterface: QueryInterface) => {
    for (const col of ['trns_uniq_no', 'tds_trns_id', 'doc_date', 'tds_amt']) {
      await queryInterface.removeColumn('form16_sap_responses', col).catch(() => {});
      await queryInterface.removeColumn('form16_debit_note_sap_responses', col).catch(() => {});
    }
  },
};
