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

async function createCompanyUser() {
  
    // Edit these values directly in code (no env vars)
    const companyEmail = 'dummy-company@profitplanet.local';
    const companyPassword = 'dummyPass!1234';
    const companyName = 'Dummy Company Inc';
    const companyPhone = '+490000000001';
    const contactPersonName = 'Dummy Contact';
    const contactPersonPhone = '+490000000002';

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

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

        if (existing.length) {
            userId = existing[0].id;
            await uow.connection.query(
                `UPDATE users SET password = ? WHERE id = ?`,
                [hashed, userId]
            );
            console.log('✅ Company user password updated');
        } else {
            // Create base user record
            const [userRes] = await uow.connection.query(
                `INSERT INTO users (email, password, user_type, role, created_at) VALUES (?, ?, 'company', 'user', NOW())`,
                [companyEmail, hashed]
            );
            userId = userRes.insertId;

            // Create company profile (adjust column names if schema differs)
            await uow.connection.query(
                `INSERT INTO company_profiles (user_id, company_name, phone, contact_person_name, contact_person_phone)
                    VALUES (?, ?, ?, ?, ?)`,
                [userId, companyName, companyPhone, contactPersonName, contactPersonPhone]
            );

            // Initialize user status (defaults: not verified, not completed)
            await uow.connection.query(
                `INSERT INTO user_status (user_id, status, is_admin_verified, email_verified, profile_completed, documents_uploaded, contract_signed)
                    VALUES (?, 'pending', 0, 0, 0, 0, 0)`,
                [userId]
            );

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

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

        await uow.commit();
        return { ok: true, userId, email: companyEmail };
    } catch (error) {
        await uow.rollback(error);
        console.error('💥 Failed to create company user:', error);
        throw error;
    }
}

module.exports = createCompanyUser;
