File size: 1,624 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
 * 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,
  });
});