-- Repair StopStatus enum values.
-- The init migration created: COMPLETED, APPROACHING, CURRENT, UPCOMING
-- The current Prisma schema expects: OPEN, CHECKIN_CLOSED, BOARDED, COMPLETED
-- Migration 20260717000001 was supposed to rename these directly but its SQL
-- file is empty (marked "already applied"), so the rename may not have run
-- on all deployed environments. This migration is idempotent: it only renames
-- a value if the old label still exists in pg_enum.

DO $$
DECLARE
  v_has_upcoming    boolean;
  v_has_approaching boolean;
  v_has_current     boolean;
BEGIN
  SELECT EXISTS (
    SELECT 1 FROM pg_enum e
    JOIN pg_type t ON e.enumtypid = t.oid
    JOIN pg_namespace n ON t.typnamespace = n.oid
    WHERE n.nspname = 'passenger' AND t.typname = 'StopStatus' AND e.enumlabel = 'UPCOMING'
  ) INTO v_has_upcoming;

  SELECT EXISTS (
    SELECT 1 FROM pg_enum e
    JOIN pg_type t ON e.enumtypid = t.oid
    JOIN pg_namespace n ON t.typnamespace = n.oid
    WHERE n.nspname = 'passenger' AND t.typname = 'StopStatus' AND e.enumlabel = 'APPROACHING'
  ) INTO v_has_approaching;

  SELECT EXISTS (
    SELECT 1 FROM pg_enum e
    JOIN pg_type t ON e.enumtypid = t.oid
    JOIN pg_namespace n ON t.typnamespace = n.oid
    WHERE n.nspname = 'passenger' AND t.typname = 'StopStatus' AND e.enumlabel = 'CURRENT'
  ) INTO v_has_current;

  IF v_has_upcoming THEN
    ALTER TYPE passenger."StopStatus" RENAME VALUE 'UPCOMING' TO 'OPEN';
  END IF;

  IF v_has_approaching THEN
    ALTER TYPE passenger."StopStatus" RENAME VALUE 'APPROACHING' TO 'CHECKIN_CLOSED';
  END IF;

  IF v_has_current THEN
    ALTER TYPE passenger."StopStatus" RENAME VALUE 'CURRENT' TO 'BOARDED';
  END IF;
END $$;

-- Reset column default to the current enum label name.
-- If the old label 'UPCOMING' was just renamed to 'OPEN', the stored DEFAULT
-- string 'UPCOMING' becomes invalid and must be updated.
ALTER TABLE passenger."TripStopTime" ALTER COLUMN "status" DROP DEFAULT;
ALTER TABLE passenger."TripStopTime" ALTER COLUMN "status" SET DEFAULT 'OPEN';
