import { QueryInterface, DataTypes } from 'sequelize';

/**
 * Helper function to check if a column exists in a table
 */
async function columnExists(
  queryInterface: QueryInterface,
  tableName: string,
  columnName: string
): Promise<boolean> {
  try {
    const tableDescription = await queryInterface.describeTable(tableName);
    return columnName in tableDescription;
  } catch (error) {
    return false;
  }
}

export async function up(queryInterface: QueryInterface): Promise<void> {
  const columnsToRemove = [
    'dms_number',
    'e_invoice_number',
    'e_invoice_date',
    'credit_note_number',
    'credit_note_date',
    'credit_note_amount',
  ];

  // Only remove columns if they exist
  // This handles the case where dealer_claim_details was created without these columns
  for (const columnName of columnsToRemove) {
    const exists = await columnExists(queryInterface, 'dealer_claim_details', columnName);
    if (exists) {
      await queryInterface.removeColumn('dealer_claim_details', columnName);
      console.log(`  ✅ Removed column: ${columnName}`);
    } else {
      console.log(`  ⏭️  Column ${columnName} does not exist, skipping...`);
    }
  }
}

export async function down(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.addColumn('dealer_claim_details', 'dms_number', {
    type: DataTypes.STRING(100),
    allowNull: true,
  });
  await queryInterface.addColumn('dealer_claim_details', 'e_invoice_number', {
    type: DataTypes.STRING(100),
    allowNull: true,
  });
  await queryInterface.addColumn('dealer_claim_details', 'e_invoice_date', {
    type: DataTypes.DATEONLY,
    allowNull: true,
  });
  await queryInterface.addColumn('dealer_claim_details', 'credit_note_number', {
    type: DataTypes.STRING(100),
    allowNull: true,
  });
  await queryInterface.addColumn('dealer_claim_details', 'credit_note_date', {
    type: DataTypes.DATEONLY,
    allowNull: true,
  });
  await queryInterface.addColumn('dealer_claim_details', 'credit_note_amount', {
    type: DataTypes.DECIMAL(15, 2),
    allowNull: true,
  });
}

