import { QueryInterface, DataTypes } from 'sequelize';

module.exports = {
  up: async (queryInterface: QueryInterface) => {
    // 1. Update claim_credit_notes table with idempotency checks
    const tableDefinition = await queryInterface.describeTable('claim_credit_notes');

    if (!tableDefinition.transaction_no) {
      await queryInterface.addColumn('claim_credit_notes', 'transaction_no', {
        type: DataTypes.STRING(100),
        allowNull: true,
        comment: 'Overall PWC transaction unique number'
      });
    }

    if (!tableDefinition.tds_amount) {
      await queryInterface.addColumn('claim_credit_notes', 'tds_amount', {
        type: DataTypes.DECIMAL(15, 2),
        allowNull: true,
        defaultValue: 0,
        comment: 'TDS amount for the credit note'
      });
    }

    if (!tableDefinition.credit_amount) {
      await queryInterface.addColumn('claim_credit_notes', 'credit_amount', {
        type: DataTypes.DECIMAL(15, 2),
        allowNull: true,
        defaultValue: 0,
        comment: 'Final credit amount after TDS'
      });
    }

    // Drop redundant columns if they exist
    const columnsToDrop = [
      'gst_rate', 'gst_amt', 'cgst_rate', 'cgst_amt', 
      'sgst_rate', 'sgst_amt', 'igst_rate', 'igst_amt', 
      'utgst_rate', 'utgst_amt', 'cess_rate', 'cess_amt', 
      'total_amt'
    ];

    for (const column of columnsToDrop) {
      if (tableDefinition[column]) {
        await queryInterface.removeColumn('claim_credit_notes', column);
      }
    }

    // 2. Create claim_credit_note_items table (Refined & Unified)
    const allTables = await queryInterface.showAllTables();
    const tableExists = allTables.some(t => {
        const name = typeof t === 'string' ? t : (t as any).tableName;
        return name.toLowerCase() === 'claim_credit_note_items';
    });

    if (!tableExists) {
        await queryInterface.createTable('claim_credit_note_items', {
          item_id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true,
          },
          credit_note_id: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
              model: 'claim_credit_notes',
              key: 'credit_note_id',
            },
            onDelete: 'CASCADE',
            onUpdate: 'CASCADE',
          },
          sl_no: {
            type: DataTypes.INTEGER,
            allowNull: false,
          },
          transaction_no: {
            type: DataTypes.STRING(100),
            allowNull: true,
            comment: 'Per-item TRNS_UNIQ_NO'
          },
          description: {
            type: DataTypes.TEXT,
            allowNull: true,
          },
          hsn_cd: {
            type: DataTypes.STRING(20),
            allowNull: true,
          },
          amount: {
            type: DataTypes.DECIMAL(15, 2),
            allowNull: false,
            defaultValue: 0,
          },
          claim_amount: {
            type: DataTypes.DECIMAL(15, 2),
            allowNull: true,
            defaultValue: 0,
          },
          tds_amount: {
            type: DataTypes.DECIMAL(15, 2),
            allowNull: true,
            defaultValue: 0,
          },
          credit_amount: {
            type: DataTypes.DECIMAL(15, 2),
            allowNull: true,
            defaultValue: 0,
          },
          created_at: {
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: DataTypes.NOW,
          },
          updated_at: {
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: DataTypes.NOW,
          }
        });

        // Add index for performance
        await queryInterface.addIndex('claim_credit_note_items', ['credit_note_id']);
        await queryInterface.addIndex('claim_credit_note_items', ['transaction_no']);
    }
  },

  down: async (queryInterface: QueryInterface) => {
    // Drop the items table first
    await queryInterface.dropTable('claim_credit_note_items');

    // Re-add dropped columns to claim_credit_notes (if they were removed)
    const tableDefinition = await queryInterface.describeTable('claim_credit_notes');
    const columnsToReAdd = [
      { name: 'gst_rate', type: DataTypes.DECIMAL(5, 2) },
      { name: 'gst_amt', type: DataTypes.DECIMAL(15, 2) },
      { name: 'cgst_rate', type: DataTypes.DECIMAL(5, 2) },
      { name: 'cgst_amt', type: DataTypes.DECIMAL(15, 2) },
      { name: 'sgst_rate', type: DataTypes.DECIMAL(5, 2) },
      { name: 'sgst_amt', type: DataTypes.DECIMAL(15, 2) },
      { name: 'igst_rate', type: DataTypes.DECIMAL(5, 2) },
      { name: 'igst_amt', type: DataTypes.DECIMAL(15, 2) },
      { name: 'utgst_rate', type: DataTypes.DECIMAL(5, 2) },
      { name: 'utgst_amt', type: DataTypes.DECIMAL(15, 2) },
      { name: 'cess_rate', type: DataTypes.DECIMAL(5, 2) },
      { name: 'cess_amt', type: DataTypes.DECIMAL(15, 2) },
      { name: 'total_amt', type: DataTypes.DECIMAL(15, 2) }
    ];

    for (const col of columnsToReAdd) {
      if (!tableDefinition[col.name]) {
        await queryInterface.addColumn('claim_credit_notes', col.name, {
          type: col.type,
          allowNull: true
        });
      }
    }

    // Remove added columns
    const addedCols = ['credit_amount', 'tds_amount', 'transaction_no'];
    for (const col of addedCols) {
        if (tableDefinition[col]) {
            await queryInterface.removeColumn('claim_credit_notes', col);
        }
    }
  }
};
