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

async function createJacob() {
    try {
        console.log("Creating/Updating 'Jacob' user...");
        
        const email = 'jacob@infoseclabs.io';
        const hashedPassword = await bcrypt.hash('Konyali82@', 10);
        
        // Check if exists
        const check = await db.query("SELECT id FROM users WHERE email = ?", [email]);
        
        let userId;

        if (check.rows.length > 0) {
            userId = check.rows[0].id;
            console.log(`Jacob already exists (ID: ${userId}). Updating password and verification status...`);
            await db.query("UPDATE users SET password = ?, is_verified = 1 WHERE id = ?", [hashedPassword, userId]);
        } else {
            console.log("Creating new Jacob user...");
            // Try to force ID 34 if available, otherwise auto-inc
            try {
                const res = await db.query(
                    "INSERT INTO users (id, name, username, email, password, role, is_verified) VALUES (34, ?, ?, ?, ?, ?, 1)",
                    ['Jacob', 'jacob', email, hashedPassword, 'normal']
                );
                userId = 34;
            } catch (e) {
                // Determine if error is dup entry for key PRIMARY
                console.log("Could not force ID 34 (might be taken or error), trying auto-increment...");
                const res = await db.query(
                    "INSERT INTO users (name, username, email, password, role, is_verified) VALUES (?, ?, ?, ?, ?, 1)",
                    ['Jacob', 'jacob', email, hashedPassword, 'normal']
                );
                userId = res.rows.insertId;
            }
        }
        
        // Update/Insert XP
        console.log(`Setting XP for User ID ${userId}...`);
        await db.query("DELETE FROM user_xp WHERE user_id = ?", [userId]);
        await db.query(
            "INSERT INTO user_xp (user_id, total_xp, current_level) VALUES (?, ?, ?)",
            [userId, 2200, 23]
        );
        
        console.log(`Success! User ID: ${userId}`);
        console.log("Login with:\nEmail: jacob@infoseclabs.io\nPassword: Konyali82@");
        process.exit();
    } catch (err) {
        console.error(err);
        process.exit(1);
    }
}

createJacob();
