-- Create passenger schema if it doesn't exist
CREATE SCHEMA IF NOT EXISTS passenger;

-- Move all enums from public to passenger schema
DO $$
DECLARE
  e text;
BEGIN
  FOR e IN
    SELECT typname FROM pg_type
    JOIN pg_namespace ON pg_namespace.oid = pg_type.typnamespace
    WHERE pg_namespace.nspname = 'public' AND pg_type.typtype = 'e'
  LOOP
    EXECUTE format('ALTER TYPE public.%I SET SCHEMA passenger', e);
  END LOOP;
END $$;

-- Move all tables from public to passenger schema
DO $$
DECLARE
  t text;
BEGIN
  FOR t IN
    SELECT tablename FROM pg_tables
    WHERE schemaname = 'public' AND tablename NOT IN ('_prisma_migrations')
  LOOP
    EXECUTE format('ALTER TABLE public.%I SET SCHEMA passenger', t);
  END LOOP;
END $$;

-- Add missing columns to Booking
ALTER TABLE "passenger"."Booking"
  ADD COLUMN IF NOT EXISTS "returnScheduleId"             TEXT,
  ADD COLUMN IF NOT EXISTS "returnOriginStationId"        TEXT,
  ADD COLUMN IF NOT EXISTS "returnDestinationStationId"   TEXT,
  ADD COLUMN IF NOT EXISTS "returnHoldId"                 TEXT,
  ADD COLUMN IF NOT EXISTS "returnSeatClassId"            TEXT,
  ADD COLUMN IF NOT EXISTS "leg2ScheduleId"               TEXT,
  ADD COLUMN IF NOT EXISTS "leg2OriginStationId"          TEXT,
  ADD COLUMN IF NOT EXISTS "leg2DestinationStationId"     TEXT,
  ADD COLUMN IF NOT EXISTS "leg2SeatClassId"              TEXT,
  ADD COLUMN IF NOT EXISTS "returnLeg2ScheduleId"         TEXT,
  ADD COLUMN IF NOT EXISTS "returnLeg2OriginStationId"    TEXT,
  ADD COLUMN IF NOT EXISTS "returnLeg2DestStationId"      TEXT,
  ADD COLUMN IF NOT EXISTS "returnLeg2SeatClassId"        TEXT,
  ADD COLUMN IF NOT EXISTS "outboundBoardedAt"            TIMESTAMP(3),
  ADD COLUMN IF NOT EXISTS "returnBoardedAt"              TIMESTAMP(3);

-- Add ReturnLegStatus enum and column
DO $$ BEGIN
  CREATE TYPE "passenger"."ReturnLegStatus" AS ENUM (
    'NOT_APPLICABLE', 'BOTH_USED', 'OUTBOUND_ONLY', 'INBOUND_ONLY', 'NEITHER_USED'
  );
EXCEPTION WHEN duplicate_object THEN NULL; END $$;

ALTER TABLE "passenger"."Booking"
  ADD COLUMN IF NOT EXISTS "returnLegStatus" "passenger"."ReturnLegStatus" NOT NULL DEFAULT 'NOT_APPLICABLE';

-- Add missing columns to other tables
ALTER TABLE "passenger"."GateValidationLog" ADD COLUMN IF NOT EXISTS "leg"        TEXT;
ALTER TABLE "passenger"."BookingSeat"       ADD COLUMN IF NOT EXISTS "leg"        INTEGER NOT NULL DEFAULT 1;
ALTER TABLE "passenger"."BookingSeat"       ADD COLUMN IF NOT EXISTS "scheduleId" TEXT;
ALTER TABLE "passenger"."Ticket"            ADD COLUMN IF NOT EXISTS "boardedAt"  TIMESTAMP(3);

ALTER TABLE "passenger"."SeatClass" ALTER COLUMN "baseFareMinor" SET DEFAULT 0;
ALTER TABLE "passenger"."Ticket"    ALTER COLUMN "status"        SET DEFAULT 'ACTIVE';

CREATE INDEX IF NOT EXISTS "Booking_bookingType_idx" ON "passenger"."Booking"("bookingType");
