const express = require('express');
const router = express.Router();
const db = require('../db');
const { protect } = require('../middleware/authMiddleware');

// Validate answer for a specific step
router.post('/validate-step', protect, async (req, res) => {
    const { answer } = req.body;
    const mission = parseInt(req.body.mission);
    const phase = parseInt(req.body.phase);
    let valid = false;
    let message = "Incorrect answer. Try again.";

    const lowerAnswer = answer ? answer.trim().toLowerCase() : '';

    // Mission 1: Phishing (Formerly Mission 3)
    if (mission === 1) {
        if (phase === 1 && (lowerAnswer.includes('suspicious-link.com') || lowerAnswer.includes('suspicious-link') || lowerAnswer.includes('suspicious'))) valid = true;
        if (phase === 2 && (lowerAnswer.includes('phishing') || lowerAnswer.includes('email'))) valid = true;
        if (phase === 3 && (lowerAnswer.includes('true positive') || lowerAnswer.includes('tp') || lowerAnswer.includes('true'))) valid = true;
        if (phase === 4) {
            // Very relaxed check for summary
            if (lowerAnswer.length > 5) valid = true;
        }
    }

    // Mission 2: SQL Injection (Formerly Mission 4)
    else if (mission === 2) {
        if (phase === 1 && (
            lowerAnswer.includes('sql') ||
            lowerAnswer.includes('injection') ||
            lowerAnswer.includes('sqli') ||
            lowerAnswer.includes("' or 1=1") ||
            lowerAnswer.includes('union')
        )) valid = true;
        if (phase === 2 && (lowerAnswer.includes('tor') || lowerAnswer.includes('exit node'))) valid = true;
        if (phase === 3 && (lowerAnswer.includes('true positive') || lowerAnswer.includes('tp') || lowerAnswer.includes('true') || lowerAnswer.includes('critical'))) valid = true;
        if (phase === 4) {
            // Very relaxed check for summary
            if (lowerAnswer.length > 5) valid = true;
        }
    }

    // Mission 3: Executive Summary Construction (Training Only)
    else if (mission === 3) {
        // No questions, just training. Always valid.
        valid = true;
    }

    if (valid) {
        res.json({ success: true, message: "Correct!" });
    } else {
        res.json({ success: false, message });
    }
});

// Complete a Mission (Advance to next)
router.post('/complete-mission', protect, async (req, res) => {
    try {
        const { mission } = req.body;
        // Update user's current mission progress
        await db.query('UPDATE users SET current_mission = ? WHERE id = ?', [mission + 1, req.user.id]);
        res.json({ success: true, message: "Mission Completed!" });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: "Server error" });
    }
});

// Complete All Training
router.post('/complete', protect, async (req, res) => {
    try {
        // Set current_mission to 4 to indicate fully finished beyond 3
        await db.query('UPDATE users SET training_completed = TRUE, current_mission = 4 WHERE id = ?', [req.user.id]);
        res.json({ success: true, message: "Training completed successfully!" });
    } catch (error) {
        console.error('Error completing training:', error);
        res.status(500).json({ message: "Server error" });
    }
});

module.exports = router;
