-- CreateTable: active_sessions (JWT session registry)
-- Supports concurrent-session limits and manual session revocation.
-- Using IF NOT EXISTS guards for idempotency when table was pre-created via db push.

CREATE TABLE IF NOT EXISTS "active_sessions" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "jti" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "lastSeenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "userAgent" TEXT,
    "ipAddress" TEXT,

    CONSTRAINT "active_sessions_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX IF NOT EXISTS "active_sessions_jti_key" ON "active_sessions"("jti");

-- CreateIndex
CREATE INDEX IF NOT EXISTS "active_sessions_userId_createdAt_idx" ON "active_sessions"("userId", "createdAt");

-- AddForeignKey (skip if already exists)
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.table_constraints
    WHERE constraint_name = 'active_sessions_userId_fkey'
      AND table_name = 'active_sessions'
  ) THEN
    ALTER TABLE "active_sessions"
      ADD CONSTRAINT "active_sessions_userId_fkey"
      FOREIGN KEY ("userId") REFERENCES "users"("id")
      ON DELETE CASCADE ON UPDATE CASCADE;
  END IF;
END $$;
