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

async function backfill() {
    try {
        console.log('🚀 Starting referral code backfill...');
        const users = await db.query('SELECT id FROM users WHERE referral_code IS NULL');
        console.log(`📊 Found ${users.rows.length} users with no referral code.`);

        for (const user of users.rows) {
            // Generate a short 8-char hex code
            const code = crypto.randomBytes(4).toString('hex').toUpperCase();
            await db.query('UPDATE users SET referral_code = ? WHERE id = ?', [code, user.id]);
        }

        console.log('✅ Backfill complete!');
        process.exit(0);
    } catch (error) {
        console.error('❌ Error during backfill:', error);
        process.exit(1);
    }
}

backfill();
