const UnitOfWork = require('../database/UnitOfWork');
const argon2 = require('argon2');

async function createGuestUser() {

    // Edit these values directly in code (no env vars)
    const guestEmail = 'dummy-guest@profitplanet.local';
    const guestPassword = 'dummyPass!1234';
    const firstName = 'Guest';
    const lastName = 'User';

    const uow = new UnitOfWork();
    await uow.start();
    try {
        const [existing] = await uow.connection.query(
            `SELECT id FROM users WHERE email = ? LIMIT 1`,
            [guestEmail]
        );

        const hashed = await argon2.hash(guestPassword);
        let userId;

        if (existing.length) {
            userId = existing[0].id;
            await uow.connection.query(
                `UPDATE users SET password = ?, user_type = 'personal', role = 'guest' WHERE id = ?`,
                [hashed, userId]
            );
            // Ensure personal_profile exists
            const [profileExists] = await uow.connection.query(
                `SELECT 1 FROM personal_profiles WHERE user_id = ? LIMIT 1`, [userId]
            );
            if (!profileExists.length) {
                await uow.connection.query(
                    `INSERT INTO personal_profiles (user_id, first_name, last_name) VALUES (?, ?, ?)`,
                    [userId, firstName, lastName]
                );
            }
            // Fix status: active, admin verified, email NOT verified (must verify on first login)
            await uow.connection.query(
                `UPDATE user_status SET status = 'active', is_admin_verified = 1, email_verified = 0,
                 profile_completed = 1, documents_uploaded = 1, contract_signed = 1, registration_completed = 1
                 WHERE user_id = ?`,
                [userId]
            );
            console.log('✅ Guest user updated (password, role, status fixed)');
        } else {
            // Create base user record — user_type='personal', role='guest'
            // (same pattern as GuestUserService)
            const [userRes] = await uow.connection.query(
                `INSERT INTO users (email, password, user_type, role, created_at) VALUES (?, ?, 'personal', 'guest', NOW())`,
                [guestEmail, hashed]
            );
            userId = userRes.insertId;

            // Create personal profile (required for login to return name fields)
            await uow.connection.query(
                `INSERT INTO personal_profiles (user_id, first_name, last_name) VALUES (?, ?, ?)`,
                [userId, firstName, lastName]
            );

            // Initialize user status — active, admin verified
            // email_verified = FALSE so the guest must verify email on first login
            await uow.connection.query(
                `INSERT INTO user_status (user_id, status, is_admin_verified, admin_verified_at,
                 email_verified, profile_completed, documents_uploaded, contract_signed, registration_completed)
                 VALUES (?, 'active', 1, NOW(), 0, 1, 1, 1, 1)`,
                [userId]
            );

            // Initialize user settings
            await uow.connection.query(
                `INSERT INTO user_settings (user_id) VALUES (?)`,
                [userId]
            );

            console.log('✅ Guest user created and initialized');
        }

        await uow.commit();
        console.log(`📧 Email: ${guestEmail}`);
        console.log(`🔑 Password: ${guestPassword}`);
        console.log(`🆔 User ID: ${userId}`);
        return { ok: true, userId, email: guestEmail };
    } catch (error) {
        await uow.rollback(error);
        console.error('💥 Failed to create guest user:', error);
        throw error;
    }
}

module.exports = createGuestUser;

if (require.main === module) {
    createGuestUser()
        .then(() => process.exit(0))
        .catch(() => process.exit(1));
}
