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

async function checkModuleCounts() {
    try {
        const userId = 34; // Correct user ID from previous check
        const pathId = 2; // Linux Fundamentals path ID (assuming it is path 2 based on context, or let's check modules for path 1)
        
        // Find which path module 2 belongs to
        const moduleRes = await db.query('SELECT learning_path_id FROM modules WHERE id = 2');
        const realPathId = moduleRes.rows[0].learning_path_id;
        console.log(`Module 2 belongs to Path ${realPathId}`);

        const modules = await db.query(
            'SELECT * FROM modules WHERE learning_path_id = ? AND is_active = TRUE ORDER BY display_order ASC',
            [realPathId]
        );

        for (let module of modules.rows) {
            if (module.id !== 2) continue; // Focus on module 2

            const taskCount = await db.query(
                'SELECT COUNT(*) as count FROM tasks WHERE module_id = ? AND is_active = TRUE',
                [module.id]
            );
            
            console.log(`Module ${module.id} Raw Total Count:`, taskCount.rows[0].count, typeof taskCount.rows[0].count);
            module.total_tasks = parseInt(taskCount.rows[0].count);

            const completedTasks = await db.query(
                'SELECT COUNT(*) as count FROM user_task_progress utp JOIN tasks t ON utp.task_id = t.id WHERE t.module_id = ? AND utp.user_id = ? AND utp.completed = TRUE',
                [module.id, userId]
            );
            
            console.log(`Module ${module.id} Raw Completed Count:`, completedTasks.rows[0].count, typeof completedTasks.rows[0].count);
            module.completed_tasks = parseInt(completedTasks.rows[0].count);
            
            const completionPercentage = module.total_tasks > 0
                ? Math.round((module.completed_tasks || 0) / module.total_tasks * 100)
                : 0;
            
            console.log(`Module ${module.id} Percentage: ${completionPercentage}%`);
        }
        
        process.exit(0);
    } catch (e) {
        console.error(e);
        process.exit(1);
    }
}

checkModuleCounts();
