-- Drop stale table (old schema: subject, bestScore, rank — missing elo, bestTime)
DROP TABLE IF EXISTS "LeaderboardEntry";

-- Drop orphaned table from old migration
DROP TABLE IF EXISTS "LeaderboardScore";

-- Recreate with correct schema
CREATE TABLE "LeaderboardEntry" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "grade" "Grade" NOT NULL,
    "elo" INTEGER NOT NULL DEFAULT 1000,
    "bestTime" INTEGER,
    "gamesPlayed" INTEGER NOT NULL DEFAULT 0,
    "totalCorrect" INTEGER NOT NULL DEFAULT 0,
    "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT NOW(),

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

-- Unique per user+grade (no subject)
CREATE UNIQUE INDEX "LeaderboardEntry_userId_grade_key" ON "LeaderboardEntry"("userId", "grade");

-- Foreign key
ALTER TABLE "LeaderboardEntry" ADD CONSTRAINT "LeaderboardEntry_userId_fkey"
    FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
