const db = require('../db');
const { sendAwardEmail } = require('../utils/emailService');
const badgeService = require('./badgeService');

const awardTop3 = async () => {
    try {
        // Find top 3 users by score
        const topUsersResult = await db.query(`
            SELECT u.id, u.name, u.surname, u.email, COALESCE(SUM(i.grade), 0) as total_score
            FROM users u
            LEFT JOIN investigations i ON u.id = i.user_id
            WHERE u.role != 'admin' AND u.username != 'admin'
            GROUP BY u.id
            ORDER BY total_score DESC
            LIMIT 3
        `);

        if (topUsersResult.rows.length === 0) {
            return { success: false, message: 'No users found to award.' };
        }

        const winners = topUsersResult.rows;
        const awards = ['gold', 'silver', 'bronze'];
        const results = [];

        for (let i = 0; i < winners.length; i++) {
            const winner = winners[i];
            const awardType = awards[i]; // 0=gold, 1=silver, 2=bronze

            // Define badge based on type
            let badgeName = 'Golden Analyst';
            let badgeId = 'golden_analyst';
            let badgeDesc = 'Awarded for 1st Place in the monthly leaderboard (Gold).';

            if (awardType === 'silver') {
                badgeName = 'Silver Analyst';
                badgeId = 'silver_analyst';
                badgeDesc = 'Awarded for 2nd Place in the monthly leaderboard (Silver).';
            } else if (awardType === 'bronze') {
                badgeName = 'Bronze Analyst';
                badgeId = 'bronze_analyst';
                badgeDesc = 'Awarded for 3rd Place in the monthly leaderboard (Bronze).';
            }

            // Add badge to user via service (handles deduplication and DB consistency)
            await badgeService.awardBadge(winner.id, badgeName, { checkFrequency: 'monthly' });

            // Send email notification
            try {
                await sendAwardEmail(winner.email, winner.name, awardType);
            } catch (emailError) {
                console.error(`Failed to send award email to ${winner.email}:`, emailError);
            }

            results.push(`${winner.name} (${awardType})`);
        }

        // Update system settings with the Gold winner for display
        const goldWinner = winners[0];
        const giveawayData = {
            last_winner_id: goldWinner.id,
            last_winner_name: `${goldWinner.name} ${goldWinner.surname || ''}`,
            last_awarded_at: new Date().toISOString(),
            award_type: 'gold'
        };

        await db.query(
            "INSERT INTO system_settings (`key`, value) VALUES ('giveaway', ?) ON DUPLICATE KEY UPDATE value = ?",
            [JSON.stringify(giveawayData), JSON.stringify(giveawayData)]
        );

        return { success: true, message: `Awards distributed successfully: ${results.join(', ')}`, results };
    } catch (error) {
        console.error('Error awarding top 3:', error);
        throw error;
    }
};

const resetLeaderboard = async () => {
    try {
        // Reset investigations: set grade to NULL and status to 'investigating'.
        // Setting to 'submitted' triggers auto-grader, which re-populates the leaderboard.
        // We want to clear it until manually re-submitted or just archived.
        // Setting to 'investigating' effectively pauses it.
        
        await db.query(`
            UPDATE investigations 
            SET grade = NULL, 
                status = 'investigating', 
                ai_evaluation_scheduled_at = NULL,
                feedback = NULL
            WHERE status = 'graded'
        `);
        return { success: true, message: 'Leaderboard reset successfully' };
    } catch (error) {
        console.error('Error resetting leaderboard:', error);
        throw error;
    }
};

module.exports = {
    awardTop3,
    resetLeaderboard
};
