import { NextResponse } from "next/server"; import { withApiError } from "@/lib/api-error"; import { ApiError } from "@/lib/api-error"; import { getPerformanceSummary } from "@/lib/performance"; import { generateCoachFeedback, isRateLimited, recordRequest, } from "@/lib/coach-feedback"; /** * POST /api/coach/feedback * * Returns Claude-generated personalized coaching feedback based on the * user's performance data and difficulty recommendations. * * Request body (optional): * { "userId": number } — defaults to 1 * * Response shape: * { * feedback: string, * recommendedExercise: { category: string, difficulty: string }, * encouragement: string, * cached: boolean * } * * Features: * - 3-hour response cache (keyed on user ID + rounded performance metrics) * - Rate limit: max 10 requests per user per hour * * Part 3 of the Active Coach roadmap (Issue #7). */ export const POST = withApiError(async (request) => { if (!process.env.ANTHROPIC_API_KEY) { return NextResponse.json( { error: "ANTHROPIC_API_KEY is not configured" }, { status: 503 }, ); } // Parse optional body let userId = 1; try { const body = await request.json(); if (body.userId && typeof body.userId === "number") { userId = body.userId; } } catch { // Empty body is fine — default to user 1 } // Rate limit check if (isRateLimited(userId)) { throw new ApiError(429, "Rate limit exceeded — max 10 requests per hour"); } // Get performance summary const summary = await getPerformanceSummary(userId); // Generate feedback (may return cached response) const { feedback, cached } = await generateCoachFeedback(userId, summary); // Record the request for rate limiting (only count non-cached responses, // but count all for simplicity — cached responses are fast anyway) recordRequest(userId); return NextResponse.json({ ...feedback, cached, }); });