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

// Offline submission sync endpoint
router.post("/sync/push", async (req, res) => {
  const session = getSession(req);
  if (!session || session.role !== "student") {
    return res.status(401).json({ error: "Student login required" });
  }
  const { submissions } = req.body || {};
  if (!Array.isArray(submissions)) return res.status(400).json({ error: "submissions array required" });

  const results = [];
  for (const sub of submissions) {
    try {
      const { sessionId, answers } = sub;
      if (!sessionId || !Array.isArray(answers)) { results.push({ sessionId, ok: false, error: "Invalid" }); continue; }
      const [examSession] = await query("SELECT * FROM exam_sessions WHERE id = ?", [sessionId]);
      if (!examSession || examSession.status === "graded") {
        results.push({ sessionId, ok: false, error: "Already graded or not found" });
        continue;
      }
      // Delegate to sessions submit logic
      const [exam] = await query("SELECT * FROM exams WHERE id = ?", [examSession.exam_id]);
      if (!exam) { results.push({ sessionId, ok: false, error: "Exam not found" }); continue; }
      const links = await query("SELECT * FROM exam_questions WHERE exam_id = ? ORDER BY position", [exam.id]);
      const qids = links.map(l => l.question_id);
      const questions = qids.length ? 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;
      for (const a of answers) {
        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 IGNORE INTO exam_answers (session_id, question_id, answer, is_correct, awarded_marks) VALUES (?, ?, ?, ?, ?)",
          [sessionId, q.id, a.answer || "", isCorrect, awarded]);
      }
      for (const q of questions) {
        if (!answers.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, sessionId]);
      const denom = totalMarks > 0 ? totalMarks : exam.total_marks;
      const pct = denom > 0 ? (score / denom) * 100 : 0;
      const grade = pct >= 80 ? "A" : pct >= 70 ? "B" : pct >= 60 ? "C" : pct >= 50 ? "D" : pct >= 40 ? "E" : "F";
      const remark = pct >= 80 ? "Excellent" : pct >= 70 ? "Very Good" : pct >= 60 ? "Good" : pct >= 50 ? "Average" : pct >= 40 ? "Below Average" : "Fail";
      await query("INSERT INTO exam_results (exam_id, student_id, session_id, score, total_marks, percentage, grade, remark) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
        [exam.id, examSession.student_id, sessionId, score, denom, pct, grade, remark]);
      results.push({ sessionId, ok: true });
    } catch (e) {
      results.push({ sessionId: sub.sessionId, ok: false, error: e.message });
    }
  }
  res.json({ results });
});

module.exports = router;
