const db = require('../db');

exports.saveProgress = async (req, res) => {
    try {
        const { ctfId, status, xp, lastCommand } = req.body;
        const userId = Number(req.user.id); // From request attached by auth middleware

        if (!ctfId) {
            return res.status(400).json({ message: 'CTF ID is required' });
        }

        // Check if already completed (we need to know this to prevent double XP)
        const text = `SELECT status FROM ctf_progress WHERE user_id = ? AND ctf_id = ?`;
        const existing = await db.query(text, [userId, ctfId]);

        if (existing.rows.length > 0 && existing.rows[0].status === 'completed') {
             return res.json({ message: 'Already completed', alreadyCompleted: true });
        }

        // Atomic UPSERT to avoid race conditions creating duplicates
        await db.query(`
            INSERT INTO ctf_progress (user_id, ctf_id, status, xp_awarded, last_command, completed_at)
            VALUES (?, ?, ?, ?, ?, IF(? = 'completed', NOW(), NULL))
            ON DUPLICATE KEY UPDATE 
                status = VALUES(status),
                xp_awarded = VALUES(xp_awarded),
                last_command = VALUES(last_command),
                completed_at = IF(VALUES(status) = 'completed', NOW(), completed_at)
        `, [
            userId, ctfId, 
            status || 'completed', 
            xp || 0, 
            lastCommand || '', 
            status || 'completed'
        ]);

        // If completed, optionally award XP to user profile (if not separated)
        if (status === 'completed' && xp > 0) {
             // You might have a separate logic for user total XP, 
             // but let's assume we just track it here for now or update user table if needed.
             // For example:
             // await db.query('UPDATE users SET xp = xp + ? WHERE id = ?', [xp, userId]);
        }

        res.json({ message: 'Progress saved successfully' });
    } catch (error) {
        console.error('Error saving CTF progress:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.getProgress = async (req, res) => {
    try {
        const userId = Number(req.user.id);
        const result = await db.query('SELECT * FROM ctf_progress WHERE user_id = ?', [userId]);
        res.json(result.rows);
    } catch (error) {
        console.error('Error fetching CTF progress:', error);
        res.status(500).json({ message: 'Server error' });
    }
};
