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

const fixDomains = async () => {
    console.log('🔧 Starting Student Domains Fix...');
    try {
        const domains = await db.query('SELECT id, domain FROM student_domains');
        
        for (const row of domains.rows) {
            if (row.domain.startsWith('@')) {
                const newDomain = row.domain.replace(/^@/, '').trim().toLowerCase();
                console.log(`Fixing: ${row.domain} -> ${newDomain}`);
                
                // Check if the clean version already exists (to avoid unique constraint error)
                const exists = await db.query('SELECT id FROM student_domains WHERE domain = ?', [newDomain]);
                
                if (exists.rows.length > 0) {
                    console.log(`⚠️  ${newDomain} already exists. Deleting duplicate ID ${row.id}...`);
                    await db.query('DELETE FROM student_domains WHERE id = ?', [row.id]);
                } else {
                    await db.query('UPDATE student_domains SET domain = ? WHERE id = ?', [newDomain, row.id]);
                    console.log(`✅ Updated ID ${row.id}`);
                }
            }
        }
        console.log('🎉 Domain cleanup complete.');
        process.exit(0);
    } catch (error) {
        console.error('❌ Error fixing domains:', error);
        process.exit(1);
    }
};

fixDomains();
