import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Migration: Add PENDING_BANK_TRANSFER status to csv_bookings enum
 */
export class AddPendingBankTransferStatus1740000000005 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    // Drop default before modifying enum
    await queryRunner.query(`
      ALTER TABLE "csv_bookings" ALTER COLUMN "status" DROP DEFAULT
    `);

    // Create new enum with PENDING_BANK_TRANSFER
    await queryRunner.query(`
      CREATE TYPE "csv_booking_status_new" AS ENUM (
        'PENDING_PAYMENT',
        'PENDING_BANK_TRANSFER',
        'PENDING',
        'ACCEPTED',
        'REJECTED',
        'CANCELLED'
      )
    `);

    // Swap column to new enum type
    await queryRunner.query(`
      ALTER TABLE "csv_bookings"
      ALTER COLUMN "status" TYPE "csv_booking_status_new"
      USING "status"::text::"csv_booking_status_new"
    `);

    // Drop old enum and rename new
    await queryRunner.query(`DROP TYPE "csv_booking_status"`);
    await queryRunner.query(`ALTER TYPE "csv_booking_status_new" RENAME TO "csv_booking_status"`);

    // Restore default
    await queryRunner.query(`
      ALTER TABLE "csv_bookings" ALTER COLUMN "status" SET DEFAULT 'PENDING_PAYMENT'
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Move any PENDING_BANK_TRANSFER rows back to PENDING_PAYMENT
    await queryRunner.query(`
      UPDATE "csv_bookings" SET "status" = 'PENDING_PAYMENT' WHERE "status" = 'PENDING_BANK_TRANSFER'
    `);

    await queryRunner.query(`
      ALTER TABLE "csv_bookings" ALTER COLUMN "status" DROP DEFAULT
    `);

    await queryRunner.query(`
      CREATE TYPE "csv_booking_status_old" AS ENUM (
        'PENDING_PAYMENT',
        'PENDING',
        'ACCEPTED',
        'REJECTED',
        'CANCELLED'
      )
    `);

    await queryRunner.query(`
      ALTER TABLE "csv_bookings"
      ALTER COLUMN "status" TYPE "csv_booking_status_old"
      USING "status"::text::"csv_booking_status_old"
    `);

    await queryRunner.query(`DROP TYPE "csv_booking_status"`);
    await queryRunner.query(`ALTER TYPE "csv_booking_status_old" RENAME TO "csv_booking_status"`);

    await queryRunner.query(`
      ALTER TABLE "csv_bookings" ALTER COLUMN "status" SET DEFAULT 'PENDING_PAYMENT'
    `);
  }
}
