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

export async function POST(
  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;

  // Compute score (open-ended questions are excluded from grading)
  let correctCount = 0;
  const gradableQuestions = attempt.questions.filter((q) => q.type !== "open-ended");

  for (const q of gradableQuestions) {
    const answer = answers.find((a) => a.questionId === q.id);
    const selected = answer?.selectedAnswers || [];

    if (q.type === "multiple-dropdown") {
      const allCorrect = (q.subQuestions || []).every((sq) => {
        const entry = selected.find((a) => a.startsWith(sq.id + ":"));
        return entry ? entry.split(":")[1] === sq.correctOptionId : false;
      });
      if (allCorrect) correctCount++;
    } else {
      const correct =
        selected.length === q.correctAnswers.length &&
        selected.length > 0 &&
        selected.every((s) => q.correctAnswers.includes(s));
      if (correct) correctCount++;
    }
  }

  const gradableCount = gradableQuestions.length;
  const now = new Date().toISOString();
  attempt.correctCount = correctCount;
  attempt.score = gradableCount > 0 ? Math.round((correctCount / gradableCount) * 100) : 100;
  attempt.status = "completed";
  attempt.completedAt = now;
  attempt.lastUpdatedAt = now;

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