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

/**
 * Separate table for Form 16 debit note SAP responses (OUTGOING FORM16_DBT).
 * Credit note SAP responses remain in form16_sap_responses only.
 */
module.exports = {
  up: async (queryInterface: QueryInterface) => {
    await queryInterface.createTable('form16_debit_note_sap_responses', {
      id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true,
      },
      file_name: {
        type: DataTypes.STRING(255),
        allowNull: false,
        unique: true,
      },
      debit_note_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: { model: 'form_16_debit_notes', key: 'id' },
        onDelete: 'SET NULL',
      },
      claim_number: {
        type: DataTypes.STRING(100),
        allowNull: true,
      },
      sap_document_number: {
        type: DataTypes.STRING(100),
        allowNull: true,
      },
      msg_typ: {
        type: DataTypes.STRING(20),
        allowNull: true,
      },
      message: {
        type: DataTypes.TEXT,
        allowNull: true,
      },
      raw_row: {
        type: DataTypes.JSONB,
        allowNull: true,
      },
      storage_url: {
        type: DataTypes.STRING(500),
        allowNull: true,
      },
      created_at: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: DataTypes.NOW,
      },
      updated_at: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: DataTypes.NOW,
      },
    });

    await queryInterface.addIndex('form16_debit_note_sap_responses', ['debit_note_id']);
    await queryInterface.addIndex('form16_debit_note_sap_responses', ['claim_number']);
  },

  down: async (queryInterface: QueryInterface) => {
    await queryInterface.dropTable('form16_debit_note_sap_responses');
  },
};
