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

// Get current user's XP and Stats
const getMyStats = async (req, res) => {
    try {
        const userId = Number(req.user.id);
        
        // Fetch XP, Level, Streak from user_xp
        const xpResult = await db.query('SELECT total_xp, current_level, streak_days FROM user_xp WHERE user_id = ?', [userId]);
        const xpData = xpResult.rows[0] || { total_xp: 0, current_level: 1, streak_days: 0 };

        // Fetch completed missions count
        const completedResult = await db.query("SELECT COUNT(*) as count FROM user_task_progress WHERE user_id = ? AND completed = TRUE", [userId]);
        const completedMissions = parseInt(completedResult.rows[0].count) || 0;

        res.json({
            total_xp: xpData.total_xp,
            current_level: xpData.current_level,
            streak_days: xpData.streak_days,
            completed_missions: completedMissions
        });

    } catch (error) {
        console.error('Get XP Stats Error:', error);
        res.status(500).json({ message: 'Server error retrieving XP stats' });
    }
};

// Get Skill Profile for Radar Chart
const getSkillProfile = async (req, res) => {
    try {
        const userId = Number(req.user.id);

        // Fetch all graded investigations for the user, joined with alert details
        const query = `
            SELECT a.alert_type, i.grade, a.sector_code 
            FROM investigations i
            JOIN alerts a ON i.alert_id = a.id
            WHERE i.user_id = ? AND i.status = 'graded'
        `;
        
        const result = await db.query(query, [userId]);
        const investigations = result.rows;

        // Initialize Skill Categories
        // Categories: Network, Web, Forensics, Cloud, Malware, OSINT
        const skills = {
            'Network': { score: 0, count: 0, max: 100 },
            'Web': { score: 0, count: 0, max: 100 },
            'Forensics': { score: 0, count: 0, max: 100 },
            'Cloud': { score: 0, count: 0, max: 100 },
            'Malware': { score: 0, count: 0, max: 100 },
            'OSINT': { score: 0, count: 0, max: 100 }
        };

        // Helper to map alert type/sector to skill category
        const mapToCategory = (type, sector) => {
            const t = type.toLowerCase();
            const s = (sector || '').toLowerCase();

            if (t.includes('network') || t.includes('traffic') || t.includes('ddos') || t.includes('lateral')) return 'Network';
            if (t.includes('web') || t.includes('injection') || t.includes('xss') || t.includes('csrf') || t.includes('upload')) return 'Web';
            if (t.includes('forensics') || t.includes('artifact') || t.includes('disk') || t.includes('memory')) return 'Forensics';
            if (t.includes('cloud') || s.includes('cloud') || t.includes('aws') || t.includes('azure') || t.includes('bucket')) return 'Cloud';
            if (t.includes('malware') || t.includes('ransomware') || t.includes('virus') || t.includes('trojan') || t.includes('execution')) return 'Malware';
            if (t.includes('osint') || t.includes('phishing') || t.includes('social') || t.includes('email') || t.includes('intelligence')) return 'OSINT';
            
            return 'Network'; // Default fallback
        };

        // Process Data
        investigations.forEach(inv => {
            const category = mapToCategory(inv.alert_type, inv.sector_code);
            if (skills[category]) {
                skills[category].score += inv.grade || 0;
                skills[category].count += 1;
            }
        });

        // Format for Recharts
        // Determine "FullMark" - dynamic or static?
        // Let's make it relative: Score is average grade (0-100).
        // BUT, we want to show volume too? Radar charts usually show "strength" (competency).
        // Let's stick to Average Grade for now, maybe weighted by count later.
        // Actually, let's do: (Average Grade * Log(Count + 1)) mapped to 0-100? 
        // Simple Average is safest for V1.
        
        const chartData = Object.keys(skills).map(key => {
            const data = skills[key];
            const avg = data.count > 0 ? Math.round(data.score / data.count) : 0;
            // Let's add a small bonus for experience (count), capped at 20 points
            // Bonus = min(20, count * 2)
            const bonus = Math.min(20, data.count * 2);
            // Final score capped at 100
            const finalScore = Math.min(100, avg + bonus); 

            return {
                subject: key,
                A: Math.max(10, finalScore), // Base 10 for visibility even if empty
                fullMark: 100
            };
        });

        res.json(chartData);

    } catch (error) {
        console.error('Get Skill Profile Error:', error);
        res.status(500).json({ message: 'Server error retrieving skill profile' });
    }
};

module.exports = {
    getMyStats,
    getSkillProfile
};
