import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Hotel extras Type dropdown is Extra Bed/Mattress, Child No Bed,
 * and Custom. Collapse the stored `kind` set to match:
 *
 *   CWEB          → AWEB   (child extra bed is the same extra-bed line)
 *   MEAL_UPGRADE  → CUSTOM
 *   ROOM_UPGRADE  → CUSTOM
 *
 * Then replace the CHECK constraints. down() restores the old CHECK
 * but cannot un-merge remapped rows.
 */
export class HotelExtraKindsTrim1786500000000 implements MigrationInterface {
  name = 'HotelExtraKindsTrim1786500000000';

  public async up(qr: QueryRunner): Promise<void> {
    for (const table of ['booking_hotel_extras', 'query_quote_hotel_extras']) {
      await qr.query(`UPDATE "${table}" SET "kind" = 'AWEB' WHERE "kind" = 'CWEB'`);
      await qr.query(
        `UPDATE "${table}" SET "kind" = 'CUSTOM' WHERE "kind" IN ('MEAL_UPGRADE','ROOM_UPGRADE')`,
      );
      await qr.query(`ALTER TABLE "${table}" DROP CONSTRAINT IF EXISTS "ck_${table}_kind"`);
      await qr.query(`
        ALTER TABLE "${table}"
          ADD CONSTRAINT "ck_${table}_kind"
          CHECK ("kind" IN ('AWEB','CNB','CUSTOM'))
      `);
    }
  }

  public async down(qr: QueryRunner): Promise<void> {
    for (const table of ['booking_hotel_extras', 'query_quote_hotel_extras']) {
      await qr.query(`ALTER TABLE "${table}" DROP CONSTRAINT IF EXISTS "ck_${table}_kind"`);
      await qr.query(`
        ALTER TABLE "${table}"
          ADD CONSTRAINT "ck_${table}_kind"
          CHECK ("kind" IN ('AWEB','CWEB','CNB','MEAL_UPGRADE','ROOM_UPGRADE','CUSTOM'))
      `);
    }
  }
}
