"use server";

import { revalidatePath } from "next/cache";
import { redirect, unstable_rethrow } from "next/navigation";
import { prisma } from "@/lib/db";
import { authorizeStudent, authorizeTeacher } from "@/lib/auth/rbac";
import { recordAudit } from "@/lib/audit";
import { awardXp, evaluateAchievements } from "@/lib/gamification";
import {
  quizSchema,
  quizAnswerSchema,
  fieldErrors,
} from "@/lib/validation";
import { actionError, actionSuccess, type ActionState } from "@/lib/action-state";
import {
  gradeAnswer,
  scoreAttempt,
  scaleToMaxScore,
  deadlineFor,
  isAutoGraded,
  type GradableQuestion,
  type QuizResponse,
} from "@/lib/quiz";
import type { SessionUser } from "@/lib/auth/session";
import type { Prisma } from "@prisma/client";

/**
 * Quiz mutations.
 *
 * Two audiences share this file. Authors create the paper; students sit it.
 * The authorization rule is the same one the rest of the app uses: a teacher
 * may only touch a quiz on a course they own (or a class they teach), and a
 * student may only ever touch their own attempt.
 */

function messageOf(error: unknown, fallback: string): string {
  if (error instanceof Error) return error.message;
  return fallback;
}

/** Confirm the actor may author the quiz behind an assignment. */
async function assertQuizManageable(assignmentId: string): Promise<SessionUser> {
  const actor = await authorizeTeacher();

  const assignment = await prisma.assignment.findUnique({
    where: { id: assignmentId },
    select: {
      id: true,
      title: true,
      type: true,
      course: { select: { teacherId: true, classroom: { select: { teacherId: true } } } },
    },
  });

  if (!assignment) throw new Error("Tugas tidak ditemukan.");
  if (assignment.type !== "QUIZ") throw new Error("Tugas ini bukan kuis.");

  const owns =
    actor.role === "ADMIN" ||
    assignment.course.teacherId === actor.id ||
    assignment.course.classroom?.teacherId === actor.id;

  if (!owns) throw new Error("Kamu tidak mengajar kursus ini.");

  return actor;
}

/**
 * Save a quiz: its settings and its full question set.
 *
 * The question set is replaced wholesale rather than diffed. Questions are
 * ordered and referenced by position, so editing them in place would silently
 * repoint answers on attempts that already exist — and those attempts are
 * graded records. Deleting a question cascades its answers, so a question that
 * has been answered is preserved instead of dropped.
 */
export async function saveQuizAction(
  _previous: ActionState,
  formData: FormData
): Promise<ActionState> {
  let actor: SessionUser;
  const assignmentId = String(formData.get("assignmentId") ?? "");

  try {
    actor = await assertQuizManageable(assignmentId);
  } catch (error) {
    return actionError(messageOf(error, "Tidak diizinkan."));
  }

  const rawQuestions = String(formData.get("questions") ?? "");
  let parsedQuestions: unknown;
  try {
    parsedQuestions = JSON.parse(rawQuestions);
  } catch {
    return actionError("Data soal tidak dapat dibaca.");
  }

  const parsed = quizSchema.safeParse({
    assignmentId,
    passingScore: formData.get("passingScore"),
    timeLimitMinutes: formData.get("timeLimitMinutes") || undefined,
    shuffleQuestions: formData.get("shuffleQuestions") === "on",
    allowRetakes: formData.get("allowRetakes") === "on",
    maxAttempts: formData.get("maxAttempts"),
    questions: parsedQuestions,
  });

  if (!parsed.success) {
    return actionError("Periksa kembali pengaturan kuis.", fieldErrors(parsed.error));
  }

  const data = parsed.data;

  try {
    const existing = await prisma.quiz.findUnique({
      where: { assignmentId },
      select: { id: true, questions: { select: { id: true, _count: { select: { answers: true } } } } },
    });

    const quiz = existing
      ? await prisma.quiz.update({
          where: { id: existing.id },
          data: {
            passingScore: data.passingScore,
            timeLimitMinutes: data.timeLimitMinutes || null,
            shuffleQuestions: data.shuffleQuestions,
            allowRetakes: data.allowRetakes,
            maxAttempts: data.maxAttempts,
          },
        })
      : await prisma.quiz.create({
          data: {
            assignmentId,
            passingScore: data.passingScore,
            timeLimitMinutes: data.timeLimitMinutes || null,
            shuffleQuestions: data.shuffleQuestions,
            allowRetakes: data.allowRetakes,
            maxAttempts: data.maxAttempts,
          },
        });

    // Questions the incoming set still refers to, so they can be updated in
    // place; anything answered but no longer listed is kept, not deleted.
    const keptIds = new Set(
      data.questions.map((question) => question.id).filter((id): id is string => Boolean(id))
    );

    const answeredIds = new Set(
      (existing?.questions ?? [])
        .filter((question) => question._count.answers > 0)
        .map((question) => question.id)
    );

    for (const [index, question] of data.questions.entries()) {
      const id = question.id;
      const payload = {
        prompt: question.prompt,
        type: question.type,
        options: question.options as Prisma.InputJsonValue,
        correctAnswer: question.correctAnswer as Prisma.InputJsonValue,
        explanation: question.explanation || null,
        points: question.points,
        orderIndex: index,
      };

      if (id && existing?.questions.some((row) => row.id === id)) {
        await prisma.quizQuestion.update({ where: { id }, data: payload });
      } else {
        await prisma.quizQuestion.create({ data: { ...payload, quizId: quiz.id } });
      }
    }

    // Drop questions the author removed — but only those nobody has answered.
    const removable = (existing?.questions ?? [])
      .filter((question) => !keptIds.has(question.id) && !answeredIds.has(question.id))
      .map((question) => question.id);

    if (removable.length > 0) {
      await prisma.quizQuestion.deleteMany({ where: { id: { in: removable } } });
    }

    await recordAudit({
      actorId: actor.id,
      action: existing ? "QUIZ_UPDATED" : "QUIZ_CREATED",
      entity: "Quiz",
      entityId: quiz.id,
      metadata: { assignmentId, questions: data.questions.length },
    });

    revalidatePath(`/dashboard/assignments/${assignmentId}`);
    revalidatePath(`/dashboard/quizzes/${assignmentId}`);
    revalidatePath("/dashboard/assignments");

    return actionSuccess(
      existing
        ? `Kuis diperbarui (${data.questions.length} soal).`
        : `Kuis dibuat dengan ${data.questions.length} soal.`
    );
  } catch (error) {
    return actionError(messageOf(error, "Gagal menyimpan kuis."));
  }
}

/**
 * Start a fresh attempt, or hand back the one already open.
 *
 * Returning the open attempt rather than creating a second one is what makes
 * the button safe to press twice: a student cannot end up with two papers in
 * flight and burn an attempt to a double-click.
 */
export async function startQuizAttemptAction(
  _previous: ActionState,
  formData: FormData
): Promise<ActionState> {
  let actor: SessionUser;
  try {
    actor = await authorizeStudent();
  } catch (error) {
    return actionError(messageOf(error, "Tidak diizinkan."));
  }

  const assignmentId = String(formData.get("assignmentId") ?? "");

  const assignment = await prisma.assignment.findFirst({
    where: {
      id: assignmentId,
      type: "QUIZ",
      status: "PUBLISHED",
      course: {
        OR: [
          { enrollments: { some: { studentId: actor.id } } },
          { classroom: { enrollments: { some: { studentId: actor.id, status: "ACTIVE" } } } },
        ],
      },
    },
    select: {
      id: true,
      title: true,
      dueAt: true,
      allowLate: true,
      courseId: true,
      quiz: {
        select: {
          id: true,
          maxAttempts: true,
          allowRetakes: true,
          _count: { select: { questions: true } },
        },
      },
    },
  });

  if (!assignment?.quiz) return actionError("Kuis tidak ditemukan atau belum dibuka.");
  if (assignment.quiz._count.questions === 0) return actionError("Kuis ini belum memiliki soal.");

  if (assignment.dueAt && new Date() > assignment.dueAt && !assignment.allowLate) {
    return actionError("Tenggat kuis sudah lewat.");
  }

  const open = await prisma.quizAttempt.findFirst({
    where: { quizId: assignment.quiz.id, studentId: actor.id, submittedAt: null },
    select: { id: true },
  });

  if (open) {
    revalidatePath(`/dashboard/quizzes/${assignmentId}`);
    redirect(`/dashboard/quizzes/${assignmentId}/kerjakan`);
  }

  const submittedCount = await prisma.quizAttempt.count({
    where: { quizId: assignment.quiz.id, studentId: actor.id, submittedAt: { not: null } },
  });

  const allowed = assignment.quiz.allowRetakes ? assignment.quiz.maxAttempts : 1;
  if (submittedCount >= allowed) {
    return actionError(
      assignment.quiz.allowRetakes
        ? `Kesempatan mengerjakan sudah habis (${allowed} percobaan).`
        : "Kuis ini hanya dapat dikerjakan satu kali."
    );
  }

  const attempt = await prisma.quizAttempt.create({
    data: {
      quizId: assignment.quiz.id,
      studentId: actor.id,
      attemptNo: submittedCount + 1,
      maxScore: 0,
      startedAt: new Date(),
    },
  });

  await recordAudit({
    actorId: actor.id,
    action: "QUIZ_ATTEMPT_STARTED",
    entity: "QuizAttempt",
    entityId: attempt.id,
    metadata: { assignmentId, attemptNo: attempt.attemptNo },
  });

  // Redirected here rather than by the caller. This action revalidates the
  // lobby route, which re-renders the page and remounts the client component —
  // resetting its action state to idle before an effect could ever observe the
  // success. Navigating from the server sidesteps that race entirely.
  revalidatePath(`/dashboard/quizzes/${assignmentId}`);
  redirect(`/dashboard/quizzes/${assignmentId}/kerjakan`);
}

/**
 * Mark and close one attempt.
 *
 * The attempt is graded server-side from the stored key. The browser never
 * sends an answer's correctness — only what the student chose — so a tampered
 * payload can at worst submit wrong answers.
 *
 * The resulting percentage is written to two places: the attempt, which keeps
 * the detail, and the student's `Submission`, which is what the gradebook
 * actually reads. Without the second write a quiz score would be invisible to
 * every grade and progress view in the app.
 */
export async function submitQuizAttemptAction(
  _previous: ActionState,
  formData: FormData
): Promise<ActionState> {
  let actor: SessionUser;
  try {
    actor = await authorizeStudent();
  } catch (error) {
    return actionError(messageOf(error, "Tidak diizinkan."));
  }

  const parsed = quizAnswerSchema.safeParse({
    attemptId: formData.get("attemptId"),
    answers: formData.get("answers") ?? "{}",
  });

  if (!parsed.success) {
    return actionError("Jawaban tidak dapat dibaca.", fieldErrors(parsed.error));
  }

  const { attemptId, answers } = parsed.data;

  const attempt = await prisma.quizAttempt.findFirst({
    where: { id: attemptId, studentId: actor.id },
    select: {
      id: true,
      attemptNo: true,
      startedAt: true,
      submittedAt: true,
      quiz: {
        select: {
          id: true,
          passingScore: true,
          timeLimitMinutes: true,
          questions: {
            select: { id: true, type: true, correctAnswer: true, points: true },
            orderBy: { orderIndex: "asc" },
          },
          assignment: {
            select: {
              id: true,
              title: true,
              maxScore: true,
              allowLate: true,
              dueAt: true,
              courseId: true,
            },
          },
        },
      },
    },
  });

  if (!attempt) return actionError("Percobaan tidak ditemukan.");
  if (attempt.submittedAt) return actionError("Percobaan ini sudah dikumpulkan.");

  // The browser's countdown is a courtesy. The real limit is recomputed here,
  // so a paused tab, a stopped clock, or an edited payload cannot buy time.
  //
  // A short grace window absorbs the round trip of the auto-submit that fires
  // when the clock reaches zero — a student who played fair should not be
  // failed by a slow connection. Past that window the answers are discarded
  // and the paper is marked as it stands, which is what the deadline means.
  const deadline = deadlineFor(attempt.startedAt, attempt.quiz.timeLimitMinutes);
  const graceMs = 90 * 1000;
  const beyondDeadline =
    deadline !== null && Date.now() > deadline.getTime() + graceMs;

  const questions: GradableQuestion[] = attempt.quiz.questions.map((question) => ({
    id: question.id,
    type: question.type,
    correctAnswer: question.correctAnswer,
    points: question.points,
  }));

  // Only answers to questions that belong to this quiz are considered, so an
  // injected question id cannot add points.
  const validIds = new Set(questions.map((question) => question.id));
  const graded = questions.map((question) => {
    if (beyondDeadline) return gradeAnswer(question, null);
    const raw = answers[question.id];
    const response = (raw ?? null) as QuizResponse;
    return gradeAnswer(question, validIds.has(question.id) ? response : null);
  });

  const score = scoreAttempt(questions, graded, attempt.quiz.passingScore);
  const { assignment } = attempt.quiz;

  // A quiz is marked the moment it is handed in, so the status is GRADED
  // unless a human still has to look at it. An attempt handed in after its own
  // deadline is flagged late so the teacher can see it in the gradebook.
  const isLate = assignment.dueAt !== null && new Date() > assignment.dueAt;
  const submissionScore = scaleToMaxScore(score.percentage, assignment.maxScore);

  try {
    await prisma.$transaction(async (tx) => {
      for (const answer of graded) {
        await tx.quizAnswer.upsert({
          where: {
            attemptId_questionId: { attemptId: attempt.id, questionId: answer.questionId },
          },
          create: {
            attemptId: attempt.id,
            questionId: answer.questionId,
            response: (answer.response ?? null) as Prisma.InputJsonValue,
            isCorrect: answer.isCorrect,
            pointsAwarded: answer.pointsAwarded,
          },
          update: {
            response: (answer.response ?? null) as Prisma.InputJsonValue,
            isCorrect: answer.isCorrect,
            pointsAwarded: answer.pointsAwarded,
          },
        });
      }

      await tx.quizAttempt.update({
        where: { id: attempt.id },
        data: {
          submittedAt: new Date(),
          score: score.percentage,
          maxScore: score.possible,
          passed: score.passed,
        },
      });

      // The gradebook keys on (assignmentId, studentId) and allows one row per
      // student, so a retake has to keep the better of the two rather than
      // overwrite a good attempt with a worse one.
      const existing = await tx.submission.findUnique({
        where: {
          assignmentId_studentId: { assignmentId: assignment.id, studentId: actor.id },
        },
        select: { id: true, score: true },
      });

      // A submission with no score yet cannot be "kept" over a real one.
      const previousScore = existing?.score ?? null;
      const keepExisting = previousScore !== null && previousScore >= submissionScore;

      if (!existing) {
        await tx.submission.create({
          data: {
            assignmentId: assignment.id,
            studentId: actor.id,
            content: `Kuis dikerjakan otomatis. Skor ${score.percentage}% (${score.earned}/${score.possible} poin).`,
            status: score.needsManualGrading ? "SUBMITTED" : "GRADED",
            isLate,
            submittedAt: new Date(),
            score: score.needsManualGrading ? null : submissionScore,
            gradedAt: score.needsManualGrading ? null : new Date(),
            feedback: score.needsManualGrading
              ? "Menunggu penilaian soal uraian."
              : `Dinilai otomatis. Ambang kelulusan ${attempt.quiz.passingScore}%.`,
          },
        });
      } else {
        await tx.submission.update({
          where: { id: existing.id },
          data: {
            content: `Kuis dikerjakan otomatis. Skor ${score.percentage}% (${score.earned}/${score.possible} poin).`,
            status: score.needsManualGrading ? "SUBMITTED" : "GRADED",
            isLate,
            submittedAt: new Date(),
            // Only ever raise a score, never lower it.
            ...(keepExisting
              ? {}
              : {
                  score: score.needsManualGrading ? null : submissionScore,
                  gradedAt: score.needsManualGrading ? null : new Date(),
                  feedback: score.needsManualGrading
                    ? "Menunggu penilaian soal uraian."
                    : `Dinilai otomatis. Ambang kelulusan ${attempt.quiz.passingScore}%.`,
                }),
          },
        });
      }
    });

    if (score.passed) {
      await awardXp({
        userId: actor.id,
        amount: 40,
        source: "QUIZ_PASS",
        reason: `Lulus kuis: ${assignment.title}`,
        refType: "quiz",
        refId: attempt.quiz.id,
        // Retakes are allowed (allowRetakes / maxAttempts), so this must be
        // idempotent per quiz: without it a student who passes twice — or three
        // times — is paid 40 XP each time for the same quiz.
        idempotent: true,
      });
    }

    await evaluateAchievements(actor.id);

    await recordAudit({
      actorId: actor.id,
      action: "QUIZ_ATTEMPT_SUBMITTED",
      entity: "QuizAttempt",
      entityId: attempt.id,
      metadata: {
        assignmentId: assignment.id,
        attemptNo: attempt.attemptNo,
        percentage: score.percentage,
        passed: score.passed,
        isLate,
      },
    });

    revalidatePath(`/dashboard/quizzes/${assignment.id}`);
    revalidatePath(`/dashboard/assignments/${assignment.id}`);
    revalidatePath(`/dashboard/gradebook`);
    revalidatePath(`/dashboard/grading`);
    revalidatePath("/dashboard");

    // Navigated from the server for the same reason as starting an attempt:
    // revalidating the runner's own route remounts the client component and
    // wipes the action state, so an effect could never observe the success.
    redirect(`/dashboard/quizzes/${assignment.id}/hasil/${attempt.id}`);
  } catch (error) {
    unstable_rethrow(error);
    return actionError(messageOf(error, "Gagal mengumpulkan kuis."));
  }
}

/**
 * Close an attempt whose time ran out.
 *
 * Called when a student returns to a timed paper that has already expired.
 * Answers already saved on the client are not recoverable — the browser is the
 * one holding them — so the attempt is marked with whatever the server knows,
 * which is the honest outcome and stops the attempt hanging open forever.
 */
export async function expireQuizAttemptAction(
  _previous: ActionState,
  formData: FormData
): Promise<ActionState> {
  let actor: SessionUser;
  try {
    actor = await authorizeStudent();
  } catch (error) {
    return actionError(messageOf(error, "Tidak diizinkan."));
  }

  const attemptId = String(formData.get("attemptId") ?? "");

  const attempt = await prisma.quizAttempt.findFirst({
    where: { id: attemptId, studentId: actor.id, submittedAt: null },
    select: {
      id: true,
      startedAt: true,
      quiz: {
        select: {
          id: true,
          timeLimitMinutes: true,
          passingScore: true,
          questions: { select: { id: true, type: true, correctAnswer: true, points: true } },
          assignment: { select: { id: true, title: true, maxScore: true } },
        },
      },
    },
  });

  if (!attempt) return actionError("Percobaan tidak ditemukan.");

  const deadline = deadlineFor(attempt.startedAt, attempt.quiz.timeLimitMinutes);
  if (!deadline || new Date() < deadline) {
    return actionError("Waktu pengerjaan belum habis.");
  }

  const questions: GradableQuestion[] = attempt.quiz.questions.map((question) => ({
    id: question.id,
    type: question.type,
    correctAnswer: question.correctAnswer,
    points: question.points,
  }));

  // Nothing was recovered, so every question counts as unanswered.
  const graded = questions.map((question) => gradeAnswer(question, null));
  const score = scoreAttempt(questions, graded, attempt.quiz.passingScore);
  const submissionScore = scaleToMaxScore(score.percentage, attempt.quiz.assignment.maxScore);

  try {
    await prisma.$transaction(async (tx) => {
      await tx.quizAttempt.update({
        where: { id: attempt.id },
        data: {
          submittedAt: new Date(),
          score: score.percentage,
          maxScore: score.possible,
          passed: false,
        },
      });

      const existing = await tx.submission.findUnique({
        where: {
          assignmentId_studentId: {
            assignmentId: attempt.quiz.assignment.id,
            studentId: actor.id,
          },
        },
        select: { id: true, score: true },
      });

      // A submission with no score yet cannot be "kept" over a real one.
      const previousScore = existing?.score ?? null;
      const keepExisting = previousScore !== null && previousScore >= submissionScore;

      if (!existing) {
        await tx.submission.create({
          data: {
            assignmentId: attempt.quiz.assignment.id,
            studentId: actor.id,
            content: "Waktu pengerjaan kuis habis.",
            status: "GRADED",
            submittedAt: new Date(),
            score: submissionScore,
            gradedAt: new Date(),
            feedback: "Waktu habis — jawaban tidak terkumpul.",
          },
        });
      } else if (!keepExisting) {
        await tx.submission.update({
          where: { id: existing.id },
          data: {
            content: "Waktu pengerjaan kuis habis.",
            status: "GRADED",
            submittedAt: new Date(),
            score: submissionScore,
            gradedAt: new Date(),
            feedback: "Waktu habis — jawaban tidak terkumpul.",
          },
        });
      }
    });

    await recordAudit({
      actorId: actor.id,
      action: "QUIZ_ATTEMPT_EXPIRED",
      entity: "QuizAttempt",
      entityId: attempt.id,
      metadata: { assignmentId: attempt.quiz.assignment.id },
    });

    revalidatePath(`/dashboard/quizzes/${attempt.quiz.assignment.id}`);
    revalidatePath(`/dashboard/assignments/${attempt.quiz.assignment.id}`);

    redirect(`/dashboard/quizzes/${attempt.quiz.assignment.id}/hasil/${attempt.id}`);
  } catch (error) {
    unstable_rethrow(error);
    return actionError(messageOf(error, "Gagal menutup percobaan."));
  }
}

/**
 * Mark a quiz question by hand.
 *
 * Only ever applies to questions the machine cannot score. Silently allowing it
 * on an auto-graded question would let a teacher contradict the answer key
 * without changing it, so the write is rejected instead.
 */
export async function gradeQuizAnswerAction(
  _previous: ActionState,
  formData: FormData
): Promise<ActionState> {
  const answerId = String(formData.get("answerId") ?? "");
  const points = Number(formData.get("points"));

  const answer = await prisma.quizAnswer.findUnique({
    where: { id: answerId },
    select: {
      id: true,
      questionId: true,
      attemptId: true,
      question: { select: { type: true, points: true } },
      attempt: { select: { studentId: true, quiz: { select: { assignmentId: true } } } },
    },
  });

  if (!answer) return actionError("Jawaban tidak ditemukan.");

  let actor: SessionUser;
  try {
    actor = await assertQuizManageable(answer.attempt.quiz.assignmentId);
  } catch (error) {
    return actionError(messageOf(error, "Tidak diizinkan."));
  }

  if (isAutoGraded(answer.question.type)) {
    return actionError("Soal ini dinilai otomatis dan tidak dapat diubah manual.");
  }

  if (!Number.isFinite(points) || points < 0 || points > answer.question.points) {
    return actionError(`Poin harus antara 0 dan ${answer.question.points}.`);
  }

  try {
    await prisma.quizAnswer.update({
      where: { id: answer.id },
      data: { pointsAwarded: Math.round(points), isCorrect: points >= answer.question.points },
    });

    // Recompute the attempt's total from all its answers, then push the new
    // percentage through to the gradebook the same way an automatic mark does.
    const [allAnswers, quiz] = await Promise.all([
      prisma.quizAnswer.findMany({
        where: { attemptId: answer.attemptId },
        select: { pointsAwarded: true },
      }),
      prisma.quiz.findUniqueOrThrow({
        where: { id: (await prisma.quizAttempt.findUniqueOrThrow({
          where: { id: answer.attemptId },
          select: { quizId: true },
        })).quizId },
        select: {
          passingScore: true,
          questions: { select: { points: true } },
          assignment: { select: { id: true, maxScore: true } },
        },
      }),
    ]);

    const earned = allAnswers.reduce((sum, row) => sum + row.pointsAwarded, 0);
    const possible = quiz.questions.reduce((sum, row) => sum + row.points, 0);
    const percentage = possible > 0 ? Math.round((earned / possible) * 100) : 0;
    const passed = percentage >= quiz.passingScore;
    const submissionScore = scaleToMaxScore(percentage, quiz.assignment.maxScore);

    await prisma.quizAttempt.update({
      where: { id: answer.attemptId },
      data: { score: percentage, maxScore: possible, passed },
    });

    // The submission holds the student's best attempt, and this may not be it.
    // A teacher marking a code answer on a weaker paper used to overwrite the
    // grade with that paper's lower total — a student who scored 91 on their
    // first attempt dropped to 5 because someone marked their second. The
    // other two paths into a submission both guard against this; this one did
    // not.
    const existing = await prisma.submission.findUnique({
      where: {
        assignmentId_studentId: {
          assignmentId: quiz.assignment.id,
          studentId: answer.attempt.studentId,
        },
      },
      select: { score: true },
    });

    const bestScore = existing?.score ?? null;
    const keepExisting = bestScore !== null && bestScore >= submissionScore;

    // Every answer on this attempt is now marked, so the grade is final even
    // if it is not the one that counts.
    await prisma.submission.updateMany({
      where: {
        assignmentId: quiz.assignment.id,
        studentId: answer.attempt.studentId,
      },
      data: keepExisting
        ? {
            status: "GRADED",
            gradedAt: new Date(),
            feedback: `Dinilai otomatis dan manual. Percobaan ini ${percentage}%; nilai terbaik ${bestScore} tetap dipakai.`,
          }
        : {
            status: "GRADED",
            score: submissionScore,
            gradedAt: new Date(),
            feedback: `Dinilai otomatis dan manual. Skor akhir ${percentage}%.`,
          },
    });

    await recordAudit({
      actorId: actor.id,
      action: "QUIZ_ANSWER_GRADED",
      entity: "QuizAnswer",
      entityId: answer.id,
      metadata: { points, percentage, passed },
    });

    revalidatePath(`/dashboard/quizzes/${answer.attempt.quiz.assignmentId}`);
    revalidatePath("/dashboard/grading");

    return actionSuccess(`Jawaban dinilai: ${Math.round(points)} poin.`);
  } catch (error) {
    return actionError(messageOf(error, "Gagal menilai jawaban."));
  }
}
