"use strict";
const { Router } = require("express");
const { query } = require("../db");
const router = Router();

function gradeFor(pct) {
  if (pct >= 80) return { grade: "A", remark: "Excellent" };
  if (pct >= 70) return { grade: "B", remark: "Very Good" };
  if (pct >= 60) return { grade: "C", remark: "Good" };
  if (pct >= 50) return { grade: "D", remark: "Average" };
  if (pct >= 40) return { grade: "E", remark: "Below Average" };
  return { grade: "F", remark: "Fail" };
}

router.post("/exams/:id/start", async (req, res) => {
  const id = parseInt(req.params.id);
  const { studentId } = req.body || {};
  if (!id || !studentId) return res.status(400).json({ error: "examId and studentId required" });
  const [exam] = await query("SELECT * FROM exams WHERE id = ?", [id]);
  if (!exam) return res.status(404).json({ error: "Exam not found" });
  await query("INSERT INTO exam_sessions (exam_id, student_id) VALUES (?, ?)", [id, studentId]);
  const [session] = await query("SELECT * FROM exam_sessions WHERE id = LAST_INSERT_ID()");
  res.status(201).json({
    id: session.id,
    examId: session.exam_id,
    studentId: session.student_id,
    startedAt: new Date(session.started_at).toISOString(),
    submittedAt: null,
    status: session.status,
  });
});

router.post("/sessions/:id/submit", async (req, res) => {
  const id = parseInt(req.params.id);
  const { answers } = req.body || {};
  if (!id) return res.status(400).json({ error: "Invalid session id" });

  const [session] = await query("SELECT * FROM exam_sessions WHERE id = ?", [id]);
  if (!session) return res.status(404).json({ error: "Session not found" });
  const [exam] = await query("SELECT * FROM exams WHERE id = ?", [session.exam_id]);
  if (!exam) return res.status(404).json({ error: "Exam not found" });

  const links = await query("SELECT * FROM exam_questions WHERE exam_id = ? ORDER BY position", [exam.id]);
  let questions = [];
  if (links.length) {
    const qids = links.map(l => l.question_id);
    questions = await query(`SELECT * FROM questions WHERE id IN (${qids.map(() => "?").join(",")})`, qids);
  }
  const qMap = new Map(questions.map(q => [q.id, q]));

  let score = 0;
  let totalMarks = 0;
  const answersArr = Array.isArray(answers) ? answers : [];

  for (const a of answersArr) {
    const q = qMap.get(a.questionId);
    if (!q) continue;
    totalMarks += q.marks;
    let awarded = 0;
    let isCorrect = null;
    if (q.type === "objective" && q.correct_answer) {
      isCorrect = a.answer.trim().toUpperCase() === q.correct_answer.trim().toUpperCase() ? 1 : 0;
      if (isCorrect) awarded = q.marks;
    }
    score += awarded;
    await query("INSERT INTO exam_answers (session_id, question_id, answer, is_correct, awarded_marks) VALUES (?, ?, ?, ?, ?)",
      [id, q.id, a.answer || "", isCorrect, awarded]);
  }

  // Count unanswered questions' marks
  for (const q of questions) {
    if (!answersArr.find(a => a.questionId === q.id)) totalMarks += q.marks;
  }

  const now = new Date().toISOString().slice(0, 19).replace("T", " ");
  await query("UPDATE exam_sessions SET status = 'graded', submitted_at = ? WHERE id = ?", [now, id]);

  const denom = totalMarks > 0 ? totalMarks : exam.total_marks;
  const percentage = denom > 0 ? (score / denom) * 100 : 0;
  const band = gradeFor(percentage);

  await query("INSERT INTO exam_results (exam_id, student_id, session_id, score, total_marks, percentage, grade, remark) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
    [exam.id, session.student_id, id, score, denom, percentage, band.grade, band.remark]);
  const [result] = await query("SELECT * FROM exam_results WHERE id = LAST_INSERT_ID()");

  const [subject] = await query("SELECT name FROM subjects WHERE id = ?", [exam.subject_id]);
  const [student] = await query("SELECT first_name, last_name FROM students WHERE id = ?", [session.student_id]);

  if (student) {
    await query("INSERT INTO activity_log (type, message) VALUES (?, ?)",
      ["result", `${student.first_name} ${student.last_name} scored ${score}/${denom} on ${exam.title}`]);
  }

  res.json({
    id: result.id,
    examId: result.exam_id,
    examTitle: exam.title,
    subjectName: subject?.name ?? null,
    studentId: result.student_id,
    studentName: student ? `${student.first_name} ${student.last_name}` : null,
    score: result.score,
    totalMarks: result.total_marks,
    percentage: Math.round(result.percentage * 100) / 100,
    grade: result.grade,
    remark: result.remark,
    submittedAt: new Date(result.submitted_at).toISOString(),
  });
});

module.exports = router;
