/**
 * Form 16 Debit Notes: issued when RE withdraws a credit note (e.g. duplicate/wrong).
 * One debit note per withdrawn credit note. SAP document number filled when SAP API is integrated.
 */

import { QueryInterface, DataTypes } from 'sequelize';

export async function up(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.createTable('form_16_debit_notes', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    credit_note_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'form_16_credit_notes', key: 'id' },
      onDelete: 'CASCADE',
      unique: true,
    },
    debit_note_number: {
      type: DataTypes.STRING(50),
      allowNull: false,
      unique: true,
    },
    sap_document_number: {
      type: DataTypes.STRING(50),
      allowNull: true,
    },
    amount: {
      type: DataTypes.DECIMAL(15, 2),
      allowNull: false,
    },
    issue_date: {
      type: DataTypes.DATEONLY,
      allowNull: false,
    },
    status: {
      type: DataTypes.STRING(20),
      allowNull: false,
      defaultValue: 'pending',
    },
    reason: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    created_by: {
      type: DataTypes.UUID,
      allowNull: true,
      references: { model: 'users', key: 'user_id' },
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
    updated_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
  });

  await queryInterface.addIndex('form_16_debit_notes', ['credit_note_id'], {
    name: 'idx_form_16_debit_notes_credit_note_id',
  });
  await queryInterface.addIndex('form_16_debit_notes', ['status'], {
    name: 'idx_form_16_debit_notes_status',
  });
}

export async function down(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.dropTable('form_16_debit_notes');
}
