-- WHMCS Phase D: SSO tickets and impersonation sessions

CREATE TYPE "SsoTicketKind" AS ENUM ('SERVICE', 'ADMIN');

ALTER TABLE "user_sessions"
  ADD COLUMN IF NOT EXISTS "isImpersonation" BOOLEAN NOT NULL DEFAULT false,
  ADD COLUMN IF NOT EXISTS "impersonationMetadata" JSONB;

CREATE TABLE IF NOT EXISTS "sso_tickets" (
  "id" TEXT NOT NULL,
  "installationId" TEXT NOT NULL,
  "tokenHash" TEXT NOT NULL,
  "kind" "SsoTicketKind" NOT NULL,
  "userId" TEXT NOT NULL,
  "serverId" TEXT,
  "externalServiceId" TEXT,
  "externalClientId" TEXT,
  "externalUserId" TEXT,
  "targetPath" TEXT NOT NULL,
  "issuer" TEXT NOT NULL,
  "audience" TEXT NOT NULL,
  "nonce" TEXT NOT NULL,
  "expiresAt" TIMESTAMPTZ(3) NOT NULL,
  "usedAt" TIMESTAMPTZ(3),
  "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT "sso_tickets_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX IF NOT EXISTS "sso_tickets_tokenHash_key" ON "sso_tickets"("tokenHash");
CREATE UNIQUE INDEX IF NOT EXISTS "sso_tickets_nonce_key" ON "sso_tickets"("nonce");
CREATE INDEX IF NOT EXISTS "sso_tickets_expiresAt_idx" ON "sso_tickets"("expiresAt");
CREATE INDEX IF NOT EXISTS "sso_tickets_installationId_createdAt_idx"
  ON "sso_tickets"("installationId", "createdAt");

ALTER TABLE "sso_tickets"
  ADD CONSTRAINT "sso_tickets_installationId_fkey"
  FOREIGN KEY ("installationId") REFERENCES "whmcs_installations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "sso_tickets"
  ADD CONSTRAINT "sso_tickets_userId_fkey"
  FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "sso_tickets"
  ADD CONSTRAINT "sso_tickets_serverId_fkey"
  FOREIGN KEY ("serverId") REFERENCES "game_servers"("id") ON DELETE SET NULL ON UPDATE CASCADE;
