import { NextRequest, NextResponse } from "next/server" import { prisma } from "@/lib/db" import { buildFsrsCard, gradeCard, skillCodeFromGrade } from "@/lib/fsrs" export async function POST(request: NextRequest) { try { const { childId, skillCode, correct, responseMs } = await request.json() if (!childId || !skillCode) { return NextResponse.json({ error: "childId and skillCode required" }, { status: 400 }) } const existingCard = await prisma.fsrsCard.findFirst({ where: { childId, skillCode }, }) const grade = skillCodeFromGrade(correct, responseMs ?? 5000) const baseCard = buildFsrsCard({ stability: existingCard?.stability, difficulty: existingCard?.difficulty, reps: existingCard?.reps, lapses: existingCard?.lapses, due: existingCard?.dueAt, }) const { card: updatedCard } = gradeCard(baseCard, grade) if (existingCard) { await prisma.fsrsCard.update({ where: { id: existingCard.id }, data: { dueAt: updatedCard.due, stability: updatedCard.stability, difficulty: updatedCard.difficulty, reps: updatedCard.reps, lapses: updatedCard.lapses, }, }) } else { await prisma.fsrsCard.create({ data: { childId, skillCode, dueAt: updatedCard.due, stability: updatedCard.stability, difficulty: updatedCard.difficulty, reps: updatedCard.reps, lapses: updatedCard.lapses, }, }) } return NextResponse.json({ success: true }) } catch (error) { console.error("FSRS grade error:", error) return NextResponse.json({ error: "Internal error" }, { status: 500 }) } }