/** * POST /api/chess/submit * * Records a chess puzzle result and awards XP. * * Body: * puzzleId string — Lichess puzzle ID * puzzleRating number — puzzle difficulty rating * solved boolean — did the user complete the puzzle? * movesPlayed number — total moves the user attempted (incl. mistakes) * solutionLen number — number of moves in the correct solution * userId? number — defaults to 1 */ import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@/lib/db"; // import { Prisma } from "@prisma/client"; import { calculateXpGain, rollCriticalHit } from "@/lib/xp"; import { checkLevelUp } from "@/lib/progression"; import { EXERCISE_XP } from "@/config/xp"; import { processSkillUnlocks } from "@/lib/skill-unlock"; import { getMultiplierPercent } from "@/lib/multiplier"; import { getTitleForLevel } from "@/config/titles"; import { withApiError } from "@/lib/api-error"; import { processEndOfDay } from "@/lib/streak"; interface SubmitBody { puzzleId: string; puzzleRating: number; solved: boolean; movesPlayed: number; solutionLen: number; durationSecs?: number; userId?: number; } /** * Quality score (0-1) based on: * - Whether the puzzle was solved (+0.5 if solved) * - Efficiency: solved without extra moves (+0 to +0.5 based on ratio) * * If not solved, quality = 0. */ export function calcQualityScore( solved: boolean, movesPlayed: number, solutionLen: number, ): number { if (!solved) return 0; // Efficiency: ratio of correct moves to total attempts. Capped at 1. const efficiency = Math.min(1, solutionLen / Math.max(movesPlayed, solutionLen)); return 0.5 + efficiency * 0.5; } export const POST = withApiError(async (request: NextRequest) => { let body: SubmitBody; try { body = await request.json(); } catch { return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); } const { puzzleId, puzzleRating, solved, movesPlayed, solutionLen, durationSecs } = body; if (!puzzleId || typeof puzzleId !== "string") { return NextResponse.json({ error: "puzzleId is required" }, { status: 400 }); } if (typeof puzzleRating !== "number") { return NextResponse.json({ error: "puzzleRating must be a number" }, { status: 400 }); } if (typeof solved !== "boolean") { return NextResponse.json({ error: "solved must be a boolean" }, { status: 400 }); } const userId = body.userId ?? 1; const safeMovesPlayed = Math.max(1, movesPlayed ?? solutionLen ?? 1); const safeSolutionLen = Math.max(1, solutionLen ?? 1); // --- Fetch user --- const user = await prisma.user.findFirst({ where: { id: userId }, include: { categorySkills: { where: { category: "chess" } } }, }); if (!user) { return NextResponse.json({ error: "No user found" }, { status: 404 }); } const chessSkill = user.categorySkills[0]; if (!chessSkill) { return NextResponse.json( { error: "Chess CategorySkill not found" }, { status: 500 }, ); } // --- XP calculation (with skill tree multiplier) --- const qualityScore = calcQualityScore(solved, safeMovesPlayed, safeSolutionLen); const { baseXp, maxQualityBonus } = EXERCISE_XP["chess"]; const isCriticalHit = rollCriticalHit(); const multiplierPercent = await getMultiplierPercent(prisma, userId, "chess"); const xpResult = calculateXpGain({ baseXp, qualityScore, maxQualityBonus, isCriticalHit, multiplierPercent, }); // --- Level-up checks --- const userLevelResult = checkLevelUp({ currentXp: user.currentXp + xpResult.totalXp, xpToNextLevel: user.xpToNextLevel, level: user.level, }); const categoryLevelResult = checkLevelUp({ currentXp: chessSkill.currentXp + xpResult.totalXp, xpToNextLevel: chessSkill.xpToNext, level: chessSkill.level, }); // --- Title progression --- const newTitle = getTitleForLevel(userLevelResult.newLevel); const titleChanged = newTitle !== user.title; // --- Streak processing (idempotent — no-op if already run today) --- await processEndOfDay(userId); // --- Daily log bookkeeping --- const now = new Date(); const todayStart = new Date( Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()), ); const tomorrowStart = new Date(todayStart.getTime() + 86_400_000); const existingLog = await prisma.dailyLog.findFirst({ where: { userId, date: { gte: todayStart, lt: tomorrowStart } }, }); const newXpEarned = (existingLog?.xpEarned ?? 0) + xpResult.totalXp; const newActivityCount = (existingLog?.activityCount ?? 0) + 1; const goalMet = newXpEarned >= user.dailyGoalXp; // --- Persist --- let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 }; await prisma.$transaction(async (tx) => { // Sanitise optional duration: must be a positive integer number of seconds const safeDuration = typeof durationSecs === "number" && durationSecs >= 0 ? Math.round(durationSecs) : null; await tx.activity.create({ data: { userId, category: "chess", exerciseType: "puzzle", description: `Chess puzzle ${puzzleId} (rating ${puzzleRating})`, baseXp: xpResult.baseXp, qualityBonus: xpResult.qualityBonus, isCriticalHit: xpResult.isCriticalHit, totalXp: xpResult.totalXp, score: qualityScore, durationSecs: safeDuration, metadata: JSON.stringify({ puzzleId, puzzleRating, solved, movesPlayed: safeMovesPlayed, solutionLen: safeSolutionLen, }), }, }); await tx.user.update({ where: { id: userId }, data: { totalXp: user.totalXp + xpResult.totalXp, currentXp: userLevelResult.remainingXp, xpToNextLevel: userLevelResult.newXpToNextLevel, level: userLevelResult.newLevel, ...(titleChanged && { title: newTitle }), }, }); await tx.categorySkill.update({ where: { id: chessSkill.id }, data: { totalXp: chessSkill.totalXp + xpResult.totalXp, currentXp: categoryLevelResult.remainingXp, xpToNext: categoryLevelResult.newXpToNextLevel, level: categoryLevelResult.newLevel, }, }); // Auto-unlock skill tree nodes if category leveled up if (categoryLevelResult.levelsGained > 0) { unlockResult = await processSkillUnlocks( tx, userId, "chess", categoryLevelResult.newLevel, ); } if (existingLog) { await tx.dailyLog.update({ where: { id: existingLog.id }, data: { xpEarned: newXpEarned, activityCount: newActivityCount, goalMet }, }); } else { await tx.dailyLog.create({ data: { userId, date: todayStart, xpEarned: newXpEarned, activityCount: newActivityCount, goalMet, }, }); } }); return NextResponse.json({ solved, qualityScore: Math.round(qualityScore * 100) / 100, xp: { totalXp: xpResult.totalXp, baseXp: xpResult.baseXp, qualityBonus: xpResult.qualityBonus, multiplierBonus: xpResult.multiplierBonus, multiplierPercent, isCriticalHit: xpResult.isCriticalHit, }, levelUp: userLevelResult.levelsGained > 0, newLevel: userLevelResult.newLevel, categoryXp: { currentXp: categoryLevelResult.remainingXp, xpToNext: categoryLevelResult.newXpToNextLevel, level: categoryLevelResult.newLevel, levelUp: categoryLevelResult.levelsGained > 0, }, newTitle: titleChanged ? newTitle : undefined, unlocks: unlockResult.unlocked, streakFreezesGranted: unlockResult.streakFreezesGranted, }); });