const bcrypt = require('bcryptjs');
const db = require('../db');
const { sendProfileUpdateEmail, sendAccountDeletedEmail } = require('../utils/emailService');
const { formatUserUrls } = require('../utils/urlHelper');

// Get public profile by username
exports.getPublicProfile = async (req, res) => {
    try {
        const { username } = req.params;

        // Get user details (Search by username first, then fallback to name)
        const userResult = await db.query('SELECT id, username, name, profile_picture, banner_url, created_at FROM users WHERE username = ? OR name = ? LIMIT 1', [username, username]);
        const user = userResult.rows[0];

        if (!user) {
            return res.status(404).json({ message: 'User not found' });
        }

        const userId = user.id;

        // Fetch User's EARNED badges from user_badges table (deduplicated)
        const earnedBadgesResult = await db.query(`
            SELECT DISTINCT b.id, b.name, b.description, b.icon_url as icon, b.xp_reward,
                   ub.awarded_at, ub.is_pinned,
                   CASE WHEN b.xp_reward >= 500 THEN 'gold'
                        WHEN b.xp_reward >= 100 THEN 'silver'
                        ELSE 'bronze' END as type
            FROM user_badges ub
            JOIN badges b ON ub.badge_id = b.id
            WHERE ub.user_id = ?
            ORDER BY ub.is_pinned DESC, ub.awarded_at DESC
        `, [userId]);
        const badges = earnedBadgesResult.rows;

        // --- Stats ---
        // Calculate Academy XP & Level
        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 };
        
        // Count Flags
        const flagsResult = await db.query('SELECT COUNT(*) as total_flags FROM user_task_progress WHERE user_id = ? AND completed = TRUE', [userId]);
        const totalFlags = parseInt(flagsResult.rows[0].total_flags) || 0;

        // Count Graded Investigations
        const investigationsResult = await db.query('SELECT COUNT(*) as total_investigations, SUM(grade) as total_grade_score FROM investigations WHERE user_id = ? AND status IN (\'graded\', \'completed\')', [userId]);
        const totalInvestigations = parseInt(investigationsResult.rows[0].total_investigations) || 0;
        
        // --- Recent Activity (Real Data) ---
        // Combine Tasks (Flags), Badges, and Level Ups
        const limit = 50; // Fetch enough for heatmap
        
        // 1. Task Completions
        const tasks = await db.query(`
            SELECT t.title, utp.completed_at as date, t.xp_reward as xp, 'flag' as type
            FROM user_task_progress utp
            JOIN tasks t ON utp.task_id = t.id
            WHERE utp.user_id = ? AND utp.completed = TRUE
            ORDER BY utp.completed_at DESC
            LIMIT ?
        `, [userId, limit]);

        // 2. Badges (from user_badges table if exists, or parsed from user.badges JSON if legacy)
        // Assuming user_badges table is the source of truth for timestamps
        const badgeActivity = await db.query(`
            SELECT b.name as title, ub.awarded_at as date, b.xp_reward as xp, 'badge' as type
            FROM user_badges ub
            JOIN badges b ON ub.badge_id = b.id
            WHERE ub.user_id = ?
            ORDER BY ub.awarded_at DESC
            LIMIT ?
        `, [userId, limit]);

        // Combine and Sort
        let recentActivity = [...tasks.rows, ...badgeActivity.rows];
        
        // Sort by date desc
        recentActivity.sort((a, b) => new Date(b.date) - new Date(a.date));
        
        // Slice to limit
        recentActivity = recentActivity.slice(0, 50);

        // Calculate Global Rank based on XP
        const currentUserXp = xpData.total_xp || 0;
        const rankResult = await db.query(`
            SELECT COUNT(*) + 1 as \`rank\`
            FROM user_xp
            WHERE total_xp > ?
        `, [currentUserXp]);
        const calculatedRank = parseInt(rankResult.rows?.[0]?.rank) || 1;

        // 7. Skills
        const skillsResult = await db.query('SELECT skill_name, level FROM user_skills WHERE user_id = ?', [userId]);
        let skills = skillsResult.rows;

        // Fallback: If no skills recorded, generate dynamic baseline based on user level
        if (skills.length === 0) {
            const baseLevel = Math.min(80, (xpData.current_level || 1) * 2);
            skills = [
                { skill_name: 'SOC Operations', level: Math.max(10, baseLevel + 5) },
                { skill_name: 'DFIR', level: Math.max(5, baseLevel - 10) },
                { skill_name: 'Malware Analysis', level: Math.max(0, baseLevel - 20) },
                { skill_name: 'Network Security', level: Math.max(15, baseLevel + 10) },
                { skill_name: 'Threat Intel', level: Math.max(5, baseLevel - 5) },
                { skill_name: 'Cloud Security', level: Math.max(0, baseLevel - 15) }
            ];
        }

        // 8. Real Certificates (Path Completions)
        const certsResult = await db.query(`
            SELECT up.certificate_id, lp.title, up.completed_at 
            FROM user_path_progress up
            JOIN learning_paths lp ON up.learning_path_id = lp.id
            WHERE up.user_id = ? AND (up.percentage_completed = 100 OR up.completed_at IS NOT NULL)
            ORDER BY up.completed_at DESC
        `, [userId]);
        const certificates = certsResult.rows;

        // Format response
        res.json(formatUserUrls({
            username: user.username,
            profile_picture: user.profile_picture,
            banner_url: user.banner_url,
            created_at: user.created_at,
            country: null, // Removed as per request
            stats: {
                xp: xpData.total_xp,
                level: xpData.current_level,
                streak: xpData.streak_days,
                total_flags: totalFlags + totalInvestigations, // Combine flags + investigations for "total flags" visual or separate
                rank: calculatedRank
            },
            badges: badges, // Properly earned badges from user_badges table
            recent_activity: recentActivity,
            skills: skills,
            certificates: certificates
        }));

    } catch (error) {
        console.error('Get Public Profile Error:', error);
        res.status(500).json({ message: 'Server error', error: error.message, stack: error.stack });
    }
};

// Get current user's profile, including total score and graded alerts
exports.getProfile = async (req, res) => {
    try {
        const userId = Number(req.user.id);

        // Get user details
        const userResult = await db.query('SELECT id, name, surname, username, email, role, profile_picture, banner_url, subscription_plan, renewal_date as subscription_end_date, badges, created_at FROM users WHERE id = ?', [userId]);
        const user = userResult.rows[0];

        if (!user) {
            return res.status(404).json({ message: 'User not found' });
        }

        // Parse badges if string
        try {
            if (typeof user.badges === 'string') {
                user.badges = JSON.parse(user.badges);
            }
        } catch (e) {
            user.badges = [];
        }

        // Format user URLs
        const formattedUser = formatUserUrls(user);

        // Calculate stats from investigations
        const statsResult = await db.query(`
            SELECT 
                COUNT(*) as total_graded_alerts,
                SUM(grade) as total_score,
                AVG(grade) as average_score
            FROM investigations
            WHERE user_id = ? AND status IN ('graded', 'completed')
        `, [userId]);

        const stats = statsResult.rows[0];

        // Get total assigned investigations (active + closed)
        const assignedResult = await db.query('SELECT COUNT(*) as total_assigned FROM investigations WHERE user_id = ?', [userId]);

        // Get total system alerts
        const systemResult = await db.query('SELECT COUNT(*) as total_system FROM alerts');

        // Fetch graded alerts details
        // Fetch graded alerts details
        const gradedAlertsResult = await db.query(`
            SELECT a.id, a.title, i.grade, i.updated_at as graded_at 
            FROM investigations i
            JOIN alerts a ON i.alert_id = a.id
            WHERE i.user_id = ? AND i.status IN ('graded', 'completed')
            ORDER BY i.updated_at DESC
        `, [userId]);

        // --- Academy Stats ---
        // Calculate Academy XP
        const xpResult = await db.query(`
            SELECT SUM(t.xp_reward) as total_xp 
            FROM user_task_progress utp 
            JOIN tasks t ON utp.task_id = t.id 
            WHERE utp.user_id = ? AND utp.completed = TRUE
        `, [userId]);
        const academyXp = parseInt(xpResult.rows[0].total_xp) || 0;

        // Calculate Academy Grade (Average of passed lessons)
        const gradeResult = await db.query(`
            SELECT AVG(score) as average_grade 
            FROM user_lesson_grades 
            WHERE user_id = ? AND passed = TRUE
        `, [userId]);
        const academyGrade = parseFloat(gradeResult.rows[0].average_grade) || 0;

        // Calculate Level (Simple formula: 100 XP per level, starts at level 1)
        const academyLevel = Math.floor(academyXp / 100) + 1;

        // --- User XP & Streak ---
        const userXpResult = await db.query('SELECT streak_days, total_xp, current_level FROM user_xp WHERE user_id = ?', [userId]);
        const userXpData = userXpResult.rows[0] || { streak_days: 0, total_xp: 0, current_level: 1 };

        // Fetch ALL available badges for display
        const allAvailableBadgesResult = await db.query('SELECT * FROM badges ORDER BY xp_reward DESC');
        const allAvailableBadges = allAvailableBadgesResult.rows.map(b => {
             let visualType = 'bronze';
             if (b.xp_reward >= 500) visualType = 'gold';
             else if (b.xp_reward >= 100) visualType = 'silver';
             
             return {
                id: b.id,
                name: b.name,
                icon: b.icon_url,
                description: b.description,
                type: visualType,
                category: b.badge_type,
                xp_reward: b.xp_reward
            };
        });

        // --- Skill Profile Stats ---
        const completedTasksResult = await db.query(`
            SELECT t.title as task_title, m.title as module_title, t.xp_reward
            FROM user_task_progress utp
            JOIN tasks t ON utp.task_id = t.id
            JOIN modules m ON t.module_id = m.id
            WHERE utp.user_id = ? AND utp.completed = TRUE
        `, [userId]);
        const completedInvestigationsResult = await db.query(`
            SELECT a.title as alert_title, a.alert_type, i.grade
            FROM investigations i
            JOIN alerts a ON i.alert_id = a.id
            WHERE i.user_id = ? AND i.status IN ('graded', 'completed')
        `, [userId]);
        const skills = { 'Network': { score: 0 }, 'Web': { score: 0 }, 'Forensics': { score: 0 }, 'Cloud': { score: 0 }, 'Malware': { score: 0 }, 'OSINT': { score: 0 } };
        const categorize = (text) => {
            if (!text) return null; const lower = text.toLowerCase();
            if (lower.includes('network') || lower.includes('traffic') || lower.includes('pcap')) return 'Network';
            if (lower.includes('web') || lower.includes('http') || lower.includes('xss') || lower.includes('sql')) return 'Web';
            if (lower.includes('forensics') || lower.includes('memory') || lower.includes('disk')) return 'Forensics';
            if (lower.includes('cloud') || lower.includes('aws') || lower.includes('azure') || lower.includes('docker')) return 'Cloud';
            if (lower.includes('malware') || lower.includes('virus') || lower.includes('ransomware')) return 'Malware';
            if (lower.includes('osint') || lower.includes('intelligence') || lower.includes('recon')) return 'OSINT';
            return null;
        };
        completedTasksResult.rows.forEach(row => { const cat = categorize(row.module_title) || categorize(row.task_title); if (cat) skills[cat].score += 10; });
        completedInvestigationsResult.rows.forEach(row => { const cat = categorize(row.alert_type) || categorize(row.alert_title); if (cat) skills[cat].score += 25 * (row.grade / 100); });
        const skillProfile = Object.keys(skills).map(key => ({ subject: key, A: Math.min(100, Math.round(skills[key].score)), fullMark: 100 }));

        // Fetch user's EARNED badges from user_badges table (deduplicated)
        const earnedBadgesResult = await db.query(`
            SELECT DISTINCT b.id, b.name, b.description, b.icon_url, b.xp_reward,
                   ub.awarded_at,
                   CASE WHEN b.xp_reward >= 500 THEN 'gold'
                        WHEN b.xp_reward >= 100 THEN 'silver'
                        ELSE 'bronze' END as type
            FROM user_badges ub
            JOIN badges b ON ub.badge_id = b.id
            WHERE ub.user_id = ?
            ORDER BY ub.awarded_at DESC
        `, [userId]);
        const earnedBadges = earnedBadgesResult.rows;
        const earnedBadgeIds = new Set(earnedBadges.map(b => b.id));

        res.json({
            ...formattedUser,
            badges: earnedBadges, // Properly earned badges from user_badges table, deduplicated
            stats: {
                total_alerts: parseInt(assignedResult.rows[0].total_assigned),
                total_score: parseInt(stats.total_score) || 0,
                average_score: parseFloat(stats.average_score) || 0,
                total_system_alerts: parseInt(systemResult.rows[0].total_system)
            },
            academy_stats: {
                xp: userXpData.total_xp || academyXp,
                grade: academyGrade.toFixed(1),
                level: userXpData.current_level || academyLevel,
                streak_days: userXpData.streak_days || 0
            },
            graded_alerts: gradedAlertsResult.rows,
            all_badges: allAvailableBadges,
            earned_badge_ids: [...earnedBadgeIds],
            skill_profile: skillProfile
        });
    } catch (error) {
        console.error('Detailed Profile Error:', error);
        res.status(500).json({ message: 'Server error: ' + error.message });
    }
};

exports.uploadProfileImage = async (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({ message: 'Please upload a file' });
        }

        const userId = req.user.id;
        const type = req.body.type || 'avatar'; // 'avatar' or 'banner'
        const newFilePath = `/uploads/${req.file.filename}`;
        
        // Determine column and get old file
        const column = type === 'banner' ? 'banner_url' : 'profile_picture';
        const userResult = await db.query(`SELECT ${column} FROM users WHERE id = ?`, [userId]);
        const oldFileRelPath = userResult.rows[0]?.[column];

        // Update DB first
        await db.query(`UPDATE users SET ${column} = ? WHERE id = ?`, [newFilePath, userId]);

        // Cleanup old file if it exists and is local (starts with /uploads/)
        if (oldFileRelPath && oldFileRelPath.startsWith('/uploads/')) {
            const fs = require('fs');
            const path = require('path');
            const oldAbsolutePath = path.join(__dirname, '../../', oldFileRelPath); // Adjust path based on controller location
            
            // Allow async delete, don't block response
            fs.unlink(oldAbsolutePath, (err) => {
                if (err && err.code !== 'ENOENT') console.error('Failed to delete old image:', err);
            });
        }

        res.json(formatUserUrls({ 
            [column]: newFilePath,
            message: `${type === 'banner' ? 'Banner' : 'Profile picture'} updated` 
        }));
    } catch (error) {
        console.error('Upload Error:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.upgradeSubscription = async (req, res) => {
    try {
        const userId = req.user.id;
        // Set renewal date to 1 year from now
        const renewalDate = new Date();
        renewalDate.setFullYear(renewalDate.getFullYear() + 1);

        await db.query("UPDATE users SET subscription_plan = 'yearly', renewal_date = ? WHERE id = ?", [renewalDate, userId]);

        // Send email notification
        const userResult = await db.query('SELECT email, name FROM users WHERE id = ?', [userId]);
        const user = userResult.rows[0];
        const { sendSubscriptionUpgradedEmail } = require('../utils/emailService');
        await sendSubscriptionUpgradedEmail(user.email, user.name);

        res.json({ message: 'Upgraded to yearly plan', subscription_plan: 'yearly', renewal_date: renewalDate });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.cancelSubscription = async (req, res) => {
    try {
        const userId = req.user.id;
        await db.query("UPDATE users SET subscription_plan = 'free', renewal_date = NULL WHERE id = ?", [userId]);

        res.json({ message: 'Subscription cancelled', subscription_plan: 'free', renewal_date: null });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.updateAccountSettings = async (req, res) => {
    const { type, currentPassword, newPassword, newEmail } = req.body;
    const userId = req.user.id;

    try {
        // Verify current password
        const userResult = await db.query('SELECT password, email FROM users WHERE id = ?', [userId]);
        const user = userResult.rows[0];

        const isMatch = await bcrypt.compare(currentPassword, user.password);
        if (!isMatch) {
            return res.status(400).json({ message: 'Incorrect current password' });
        }

        if (type === 'password') {
            if (!newPassword || newPassword.length < 6) {
                return res.status(400).json({ message: 'New password must be at least 6 characters' });
            }
            const salt = await bcrypt.genSalt(10);
            const hashedPassword = await bcrypt.hash(newPassword, salt);
            await db.query('UPDATE users SET password = ? WHERE id = ?', [hashedPassword, userId]);

            try {
                await sendProfileUpdateEmail(user.email, 'password');
            } catch (emailErr) {
                console.error('Failed to send password update email:', emailErr);
                // Do not fail the request if email fails, just log it
            }

            return res.json({ message: 'Password updated successfully' });
        } else if (type === 'email') {
            if (!newEmail) {
                return res.status(400).json({ message: 'Please provide a new email' });
            }
            // Check if email already exists
            const emailCheck = await db.query('SELECT id FROM users WHERE email = ? AND id != ?', [newEmail, userId]);
            if (emailCheck.rows.length > 0) {
                return res.status(400).json({ message: 'Email already in use' });
            }
            await db.query('UPDATE users SET email = ? WHERE id = ?', [newEmail, userId]);

            try {
                await sendProfileUpdateEmail(user.email, 'email'); // Send to old email
                await sendProfileUpdateEmail(newEmail, 'email'); // Send to new email
            } catch (emailErr) {
                console.error('Failed to send email update notification:', emailErr);
            }

            return res.json({ message: 'Email updated successfully', email: newEmail });
        } else {
            return res.status(400).json({ message: 'Invalid update type' });
        }
    } catch (error) {
        console.error(error);
        // Clean up error message for user
        const errorMessage = error.message || 'Server error';
        res.status(500).json({ message: errorMessage });
    }
};

exports.deleteAccount = async (req, res) => {
    const userId = req.user.id;
    const { password } = req.body;

    // Start a transaction if possible, or just delete in order
    // Since we don't have explicit transaction support in this helper wrapper easily without more changes, we'll just delete in order.
    // Ideally this should be a transaction.

    try {
        const userResult = await db.query('SELECT * FROM users WHERE id = ?', [userId]);
        const user = userResult.rows[0];

        if (!user) {
            return res.status(404).json({ message: 'User not found' });
        }

        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) {
            return res.status(400).json({ message: 'Incorrect password' });
        }

        // Delete dependencies first
        await db.query('DELETE FROM investigations WHERE user_id = ?', [userId]);
        await db.query('DELETE FROM notifications WHERE user_id = ?', [userId]); // Assuming notifications table exists
        // Alerts created by user? Might be null or set to system. If foreign key is SET NULL, checking schema would be good. 
        // For now safely deleting investigations is the big one.

        await db.query('DELETE FROM users WHERE id = ?', [userId]);

        // Send email notification safely
        try {
            await sendAccountDeletedEmail(user.email, user.name);
        } catch (emailErr) {
            console.error('Failed to send account deleted email:', emailErr);
        }

        res.json({ message: 'Account deleted successfully' });
    } catch (error) {
        console.error('Delete Account Error:', error);
        res.status(500).json({ message: 'Server error: ' + (error.message || 'Unknown error') });
    }
};

// Get email preferences for current user
exports.getEmailPreferences = async (req, res) => {
    const userId = req.user.id;
    try {
        const result = await db.query('SELECT email_preferences FROM users WHERE id = ?', [userId]);
        if (result.rows.length === 0) {
            return res.status(404).json({ message: 'User not found' });
        }

        // Parse preferences or return defaults
        let preferences = result.rows[0].email_preferences;

        if (!preferences) {
            preferences = {
                weekly_report: true,
                alert_assigned: true,
                investigation_graded: true
            };
        } else if (typeof preferences === 'string') {
            try {
                preferences = JSON.parse(preferences);
            } catch (e) {
                preferences = { weekly_report: true, alert_assigned: true, investigation_graded: true };
            }
        }

        // Add newsletter status to valid preferences (check JSON first)
        if (preferences.newsletter === undefined) {
             preferences.newsletter = true; // Default to subscribed
        }

        res.json(preferences);
    } catch (error) {
        console.error('Get Email Preferences Error:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

// Update email preferences for current user
exports.updateEmailPreferences = async (req, res) => {
    const userId = req.user.id;
    const { weekly_report, alert_assigned, investigation_graded, newsletter } = req.body;

    try {
        // Build preferences object with only provided fields merged with defaults
        const currentResult = await db.query('SELECT email_preferences FROM users WHERE id = ?', [userId]);
        let current = currentResult.rows[0]?.email_preferences || {};
        if (typeof current === 'string') {
            try { current = JSON.parse(current); } catch (e) { current = {}; }
        }

        const preferences = {
            weekly_report: weekly_report !== undefined ? weekly_report : (current.weekly_report === true || current.weekly_report === undefined),
            alert_assigned: alert_assigned !== undefined ? alert_assigned : (current.alert_assigned === true || current.alert_assigned === undefined),
            investigation_graded: investigation_graded !== undefined ? investigation_graded : (current.investigation_graded === true || current.investigation_graded === undefined),
            newsletter: newsletter !== undefined ? newsletter : (current.newsletter === true || current.newsletter === undefined)
        };

        // Update JSON preferences
        await db.query('UPDATE users SET email_preferences = ? WHERE id = ?', [JSON.stringify(preferences), userId]);

        // Try to update legacy newsletter column if it exists, but don't fail if it doesn't
        if (newsletter !== undefined) {
             try {
                await db.query('UPDATE users SET is_subscribed_newsletter = ? WHERE id = ?', [newsletter ? 1 : 0, userId]);
             } catch (err) {
                // Column likely doesn't exist, ignore
             }
        }

        res.json({ message: 'Email preferences updated', preferences });
    } catch (error) {
        console.error('Update Email Preferences Error:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

// Get all badges with earned status for the current user
exports.getBadges = async (req, res) => {
    try {
        const userId = req.user.id;

        // Fetch User's Badges (Earned)
        const userBadgesResult = await db.query('SELECT badge_id, awarded_at FROM user_badges WHERE user_id = ?', [userId]);
        const earnedMap = {};
        userBadgesResult.rows.forEach(ub => {
            earnedMap[ub.badge_id] = ub.awarded_at;
        });

        // Fetch ALL Badges
        const allBadgesResult = await db.query('SELECT * FROM badges ORDER BY xp_reward ASC');
        
        const badges = allBadgesResult.rows.map(b => {
             // Determine icon name from description or name if icon_url is generic
             // This is a helper for the mobile app to map to Lucid icons
             let iconName = 'award';
             const nameLower = b.name.toLowerCase();
             
             if (nameLower.includes('login') || nameLower.includes('first')) iconName = 'star';
             else if (nameLower.includes('triage') || nameLower.includes('rookie')) iconName = 'target';
             else if (nameLower.includes('streak') || nameLower.includes('warrior')) iconName = 'flame'; // 'zap' or 'flame'
             else if (nameLower.includes('perfect') || nameLower.includes('score')) iconName = 'trophy';
             else if (nameLower.includes('level')) iconName = 'crown';
             else if (nameLower.includes('level')) iconName = 'crown';
             else if (nameLower.includes('mobile') || nameLower.includes('operative') || nameLower.includes('go')) iconName = 'smartphone';
             else if (nameLower.includes('speed') || nameLower.includes('fast')) iconName = 'zap';
             else if (nameLower.includes('night') || nameLower.includes('moon')) iconName = 'moon';
             else if (nameLower.includes('early') || nameLower.includes('morning') || nameLower.includes('day') || nameLower.includes('sun')) iconName = 'sun';
             else if (nameLower.includes('lunch') || nameLower.includes('break') || nameLower.includes('time')) iconName = 'clock';
             
             let visualType = 'bronze';
             if (b.xp_reward >= 500) visualType = 'gold';
             else if (b.xp_reward >= 100) visualType = 'silver';

             return {
                id: b.id,
                name: b.name,
                description: b.description,
                icon_url: b.icon_url,
                icon_name: iconName, // Send icon name for mobile mapping
                color: b.color || '#3B82F6', 
                xp_reward: b.xp_reward,
                earned: !!earnedMap[b.id],
                awarded_at: earnedMap[b.id] || null,
                visual_type: visualType
            };
        });

        res.json({ badges });
    } catch (error) {
        console.error('Get Badges Error:', error);
        res.status(500).json({ message: 'Server error: ' + error.message });
    }
};



