const express = require('express');
const router = express.Router();
const db = require('../lib/db');
const examContent = require('../lib/examContent');
const certificate = require('../lib/certificate');
const email = require('../lib/email');
const modules = require('../lib/modules');

// Middleware
function requireLearner(req, res, next) {
  if (!req.session.learnerId) {
    return res.redirect('/');
  }
  next();
}

// View exam
router.get('/', requireLearner, async (req, res) => {
  const learner = await db.getLearner(req.session.learnerId);
  const completedModules = await db.getCompletedModules(req.session.learnerId);

  // Check if all modules are completed
  if (completedModules.length !== modules.length) {
    return res.status(403).render('error', {
      message: 'You must complete all training modules before taking the exam.'
    });
  }

  // Check if already passed
  if (learner.passed) {
    return res.redirect('/exam/result');
  }

  res.render('exam', {
    sections: examContent.sections,
    learnerName: learner.name
  });
});

// Submit exam
router.post('/submit', requireLearner, async (req, res) => {
  const learner = await db.getLearner(req.session.learnerId);
  const completedModules = await db.getCompletedModules(req.session.learnerId);

  // Verify all modules completed
  if (completedModules.length !== modules.length) {
    return res.status(403).json({
      error: 'You must complete all training modules before taking the exam.'
    });
  }

  const answers = req.body.answers || {};

  // Score exam by section
  const sectionScores = {};
  let totalCorrect = 0;
  let totalQuestions = 0;

  examContent.sections.forEach(section => {
    let sectionCorrect = 0;
    let sectionTotal = 0;

    section.questions.forEach((question, index) => {
      const questionId = `${section.id}-${index}`;
      const userAnswer = answers[questionId] === 'true' || answers[questionId] === true;

      totalQuestions++;
      sectionTotal++;

      if (userAnswer === question.answer) {
        totalCorrect++;
        sectionCorrect++;
      }
    });

    const sectionScore = Math.round((sectionCorrect / sectionTotal) * 100);
    sectionScores[section.id] = {
      title: section.title,
      score: sectionScore,
      correct: sectionCorrect,
      total: sectionTotal,
      passed: sectionScore >= 70
    };
  });

  // Check if all sections passed
  const allSectionsPassed = Object.values(sectionScores).every(s => s.passed);
  const overallScore = Math.round((totalCorrect / totalQuestions) * 100);

  // Store result
  await db.setExamResult(
    req.session.learnerId,
    allSectionsPassed ? 1 : 0,
    JSON.stringify(sectionScores)
  );

  // Generate certificate if passed
  if (allSectionsPassed) {
    try {
      const certUrl = await certificate.generateCertificate(
        req.session.learnerId,
        learner.name,
        new Date()
      );
      await db.setCertificateUrl(req.session.learnerId, certUrl);
      email.sendCertificateEmail(learner.email, learner.name, certUrl);
    } catch (err) {
      console.error('Certificate generation error:', err);
    }
  }

  res.json({
    passed: allSectionsPassed,
    overallScore,
    sectionScores,
    totalCorrect,
    totalQuestions
  });
});

// Result page
router.get('/result', requireLearner, async (req, res) => {
  const learner = await db.getLearner(req.session.learnerId);

  if (!learner.score_json) {
    return res.redirect('/exam');
  }

  const sectionScores = JSON.parse(learner.score_json);

  res.render('result', {
    passed: learner.passed,
    sectionScores,
    learnerName: learner.name,
    certificateUrl: learner.certificate_url
  });
});

// Retake exam
router.post('/retake', requireLearner, (req, res) => {
  db.setExamRetry(req.session.learnerId);
  res.json({ success: true });
});

module.exports = router;
