import { NextResponse } from "next/server";
import { getAttempt, updateAttempt } from "@/lib/user-store";
import { QuizAnswer } from "@/types/quiz";

export async function PUT(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const attempt = await getAttempt(id);

  if (!attempt) {
    return NextResponse.json({ error: "Attempt not found" }, { status: 404 });
  }

  if (attempt.status === "completed") {
    return NextResponse.json({ error: "Attempt already completed" }, { status: 400 });
  }

  const body = await request.json();
  const { answers } = body as { answers: QuizAnswer[] };

  attempt.answers = answers;
  attempt.answeredCount = answers.filter(
    (a) => a.selectedAnswers.length > 0
  ).length;
  attempt.lastUpdatedAt = new Date().toISOString();

  await updateAttempt(attempt);
  return NextResponse.json(attempt);
}
