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

async function cleanupPath1() {
    try {
        console.log('🧹 Cleaning up Path 1 duplicates...\n');

        // 1. Delete empty duplicate modules (7, 8)
        console.log('Deleting empty duplicate modules (7, 8)...');
        await db.query('DELETE FROM modules WHERE id IN (7, 8)');

        // 2. Delete tasks for Module 3 (Old Windows)
        console.log('Deleting tasks for old Windows module (3)...');
        await db.query('DELETE FROM lesson_questions WHERE task_id IN (SELECT id FROM tasks WHERE module_id = 3)');
        await db.query('DELETE FROM lesson_content WHERE task_id IN (SELECT id FROM tasks WHERE module_id = 3)');
        await db.query('DELETE FROM tasks WHERE module_id = 3');

        // 3. Delete Module 3
        console.log('Deleting Module 3...');
        await db.query('DELETE FROM modules WHERE id = 3');

        // 4. Delete Empty placeholder modules (5, 6)
        console.log('Deleting empty placeholder modules (5, 6)...');
        // Check if they have tasks first just in case
        await db.query('DELETE FROM tasks WHERE module_id IN (5, 6)');
        await db.query('DELETE FROM modules WHERE id IN (5, 6)');

        // 5. Update display_order for remaining modules
        console.log('Reordering modules...');

        // Desired order:
        // 1. Intro (id 1)
        // 2. Linux (id 2)
        // 3. Windows (id 9)
        // 4. Networking (id 4)
        // 5. Security Principles (id 10)
        // 6. Command Line (id 11)

        const order = [
            { id: 1, order: 1 },
            { id: 2, order: 2 },
            { id: 9, order: 3 },
            { id: 4, order: 4 },
            { id: 10, order: 5 },
            { id: 11, order: 6 }
        ];

        for (const item of order) {
            await db.query('UPDATE modules SET display_order = ? WHERE id = ?', [item.order, item.id]);
            console.log(`Updated Module ${item.id} to order ${item.order}`);
        }

        console.log('\n✅ Cleanup complete!');
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}

cleanupPath1();
