import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Migration: Add PENDING_PAYMENT status to csv_bookings enum + stripe_payment_intent_id column
 */
export class AddPendingPaymentStatus1740000000004 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    // Drop the default before changing enum type
    await queryRunner.query(`
      ALTER TABLE "csv_bookings" ALTER COLUMN "status" DROP DEFAULT
    `);

    // Create new enum with PENDING_PAYMENT
    await queryRunner.query(`
      CREATE TYPE "csv_booking_status_new" AS ENUM ('PENDING_PAYMENT', '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"`);

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

    // Add stripe_payment_intent_id column
    await queryRunner.query(`
      ALTER TABLE "csv_bookings"
      ADD COLUMN IF NOT EXISTS "stripe_payment_intent_id" VARCHAR(255)
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Remove stripe_payment_intent_id column
    await queryRunner.query(`
      ALTER TABLE "csv_bookings" DROP COLUMN IF EXISTS "stripe_payment_intent_id"
    `);

    // Update any PENDING_PAYMENT rows to PENDING
    await queryRunner.query(`
      UPDATE "csv_bookings" SET "status" = 'PENDING' WHERE "status" = 'PENDING_PAYMENT'
    `);

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

    // Recreate original enum without PENDING_PAYMENT
    await queryRunner.query(`
      CREATE TYPE "csv_booking_status_old" AS ENUM ('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'
    `);
  }
}
