/** * POST /api/chess/challenge * * Creates a Stockfish bot challenge on Lichess and returns the game URL. * The user plays the game externally on Lichess, then reports the result * via POST /api/chess/game-result to earn XP. * * Body: * level number — Stockfish level 1 (easiest) → 8 (strongest). Default: 4. * userId number — defaults to 1 */ import { NextRequest, NextResponse } from "next/server"; import { challengeStockfish } from "@/lib/lichess"; import { withApiError, ApiError } from "@/lib/api-error"; interface ChallengeBody { level?: number; userId?: number; } /** * Clamps a Stockfish level to the valid range [1, 8], defaulting to 4. * Exported for unit testing. */ export function clampStockfishLevel(level: unknown): number { return typeof level === "number" ? Math.max(1, Math.min(8, Math.round(level))) : 4; } export const POST = withApiError(async (request: NextRequest) => { let body: ChallengeBody = {}; try { body = await request.json(); } catch { // body is optional — defaults are fine } const level = clampStockfishLevel(body.level); if (!process.env.LICHESS_API_TOKEN) { throw new ApiError( 503, "LICHESS_API_TOKEN is not configured. Set it in .env to enable Stockfish challenges.", ); } const challenge = await challengeStockfish(level); if (!challenge) { throw new ApiError( 502, "Failed to create Stockfish challenge on Lichess. Check your API token and try again.", ); } return NextResponse.json({ gameId: challenge.id, gameUrl: challenge.url, level, }); });