import { type MigrationInterface, type QueryRunner } from 'typeorm';

/**
 * activity_ticket_slots — multiple time windows per ticket.
 *
 * activity_tickets.time_slot was a single varchar(100). Real tickets
 * carry multiple disjoint windows — e.g. Ain Dubai's "Non-Prime Time"
 * ticket runs 10:00 AM–4 PM AND 7:30–8 PM (two separate availability
 * windows for the same pricing tier). The old column couldn't model
 * that; ops had to comma-join the windows into a label.
 *
 * Each row:
 *   - `label`      — human-readable, what ops/customer sees (e.g.
 *                    "10:00 AM - 4:00 PM"). Kept verbatim because the
 *                    source data uses inconsistent 12/24h formats and
 *                    the FE doesn't need to re-render.
 *   - `start_time` — parsed 24h HH:MM:SS where possible; NULL when the
 *                    source label is ambiguous (e.g. departure list
 *                    "09:00, 10:30, 16:00, 17:30" stored per-departure
 *                    with end_time=NULL, or fully prose labels).
 *   - `end_time`   — NULL for single-departure slots (Yellow Boat).
 *   - `sort_order` — display order; ops can reorder via UI later.
 *
 * activity_tickets.time_slot is retained for backward compatibility:
 * the seeder + ticket save path continue to write a comma-joined
 * label there so callers reading the old column see the same string.
 * Code reading the new table is the going-forward source of truth.
 */
export class ActivityTicketSlots1781500000000 implements MigrationInterface {
  public async up(qr: QueryRunner): Promise<void> {
    await qr.query(`
      CREATE TABLE activity_ticket_slots (
        id          uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
        tenant_id   uuid NOT NULL,
        ticket_id   uuid NOT NULL REFERENCES activity_tickets(id) ON DELETE CASCADE,
        label       varchar(100) NOT NULL,
        start_time  time,
        end_time    time,
        sort_order  integer NOT NULL DEFAULT 0,
        is_deleted  boolean NOT NULL DEFAULT false,
        created_by  uuid,
        updated_by  uuid,
        created_at  timestamptz NOT NULL DEFAULT now(),
        updated_at  timestamptz NOT NULL DEFAULT now()
      );
    `);
    await qr.query(`
      CREATE INDEX idx_activity_ticket_slots_tenant_ticket
        ON activity_ticket_slots (tenant_id, ticket_id) WHERE is_deleted = false;
    `);
    await qr.query(`
      CREATE UNIQUE INDEX uq_activity_ticket_slots_ticket_label
        ON activity_ticket_slots (tenant_id, ticket_id, label)
       WHERE is_deleted = false;
    `);
  }

  public async down(qr: QueryRunner): Promise<void> {
    await qr.query(`DROP INDEX IF EXISTS uq_activity_ticket_slots_ticket_label;`);
    await qr.query(`DROP INDEX IF EXISTS idx_activity_ticket_slots_tenant_ticket;`);
    await qr.query(`DROP TABLE IF EXISTS activity_ticket_slots;`);
  }
}
