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

/**
 * Stores SAP/WFM outgoing response files for Form 16 credit/debit notes.
 * Used for:
 * - Showing "credit note is being generated, wait" until SAP response is received
 * - Allowing users to download the SAP response file later
 */
module.exports = {
  up: async (queryInterface: QueryInterface) => {
    await queryInterface.createTable('form16_sap_responses', {
      id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true,
      },
      type: {
        type: DataTypes.STRING(10),
        allowNull: false, // 'credit' | 'debit'
      },
      file_name: {
        type: DataTypes.STRING(255),
        allowNull: false,
        unique: true,
      },
      credit_note_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: { model: 'form_16_credit_notes', key: 'id' },
        onDelete: 'SET NULL',
      },
      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_sap_responses', ['type']);
    await queryInterface.addIndex('form16_sap_responses', ['credit_note_id']);
    await queryInterface.addIndex('form16_sap_responses', ['debit_note_id']);
    await queryInterface.addIndex('form16_sap_responses', ['claim_number']);
  },

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

