-- Migration: 20260513_oauth_pending_states
-- Creates oauth_pending_states table for PKCE-state storage during Microsoft OAuth flow.
--
-- TTL: entries are short-lived (10 min max). The backend deletes state on callback.
-- Expired entries are garbage-collected at INSERT time in the endpoint (clean-on-write pattern).
-- No background cron needed at this scale.
--
-- Breaking-change status: NONE — new table, no existing rows affected.
-- Deploy: pnpm prisma migrate deploy (on server via GitHub Actions pipeline)

CREATE TABLE "rebreak"."oauth_pending_states" (
  "id"            UUID        NOT NULL DEFAULT gen_random_uuid(),
  "state_id"      TEXT        NOT NULL,
  "user_id"       UUID        NOT NULL,
  "code_verifier" TEXT        NOT NULL,
  "email"         TEXT,
  "created_at"    TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  CONSTRAINT "oauth_pending_states_pkey" PRIMARY KEY ("id"),
  CONSTRAINT "oauth_pending_states_state_id_key" UNIQUE ("state_id")
);

-- Index for state_id lookup on callback (O(1) by state_id)
CREATE INDEX "oauth_pending_states_state_id_idx" ON "rebreak"."oauth_pending_states" ("state_id");

-- Index for cleanup of expired entries per user
CREATE INDEX "oauth_pending_states_created_at_idx" ON "rebreak"."oauth_pending_states" ("created_at");
