import { NextRequest, NextResponse } from 'next/server' import prisma from '@/lib/prisma' import { getMobileUserId } from '@/lib/mobile-auth' import { computeSm2Update } from '@/lib/flashcards/sm2' export async function POST(req: NextRequest) { const userId = getMobileUserId(req) if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) const body = await req.json() const cardId = typeof body.cardId === 'string' ? body.cardId : null const grade = typeof body.grade === 'number' ? body.grade : null if (!cardId || grade === null || grade < 1 || grade > 4) { return NextResponse.json({ error: 'cardId and grade (1–4) required' }, { status: 400 }) } const card = await prisma.flashcard.findFirst({ where: { id: cardId, deck: { userId } }, select: { id: true, interval: true, easinessFactor: true }, }) if (!card) return NextResponse.json({ error: 'Card not found' }, { status: 404 }) const { easinessFactor, interval, nextReviewAt } = computeSm2Update(grade, { easinessFactor: card.easinessFactor, interval: card.interval, }) await prisma.$transaction([ prisma.flashcard.update({ where: { id: cardId }, data: { easinessFactor, interval, nextReviewAt }, }), prisma.flashcardReview.create({ data: { cardId, grade, reviewedAt: new Date() }, }), ]) return NextResponse.json({ ok: true, nextReviewAt, interval }) }