
import bcrypt from 'bcrypt';
import crypto from 'crypto';
import { pool } from '../db.js';

export async function seedUsers() {
    console.log('👤 Seeding users (Core Architecture)...');

    try {
        // Fetch core companies to map users
        const companiesResult = await pool.query('SELECT id, name FROM core_companies');
        const companyMap = {}; // name -> id
        companiesResult.rows.forEach(c => companyMap[c.name] = c.id);
        const systemTenantId = '00000000-0000-0000-0000-000000000000';

        // 1. Create SuperAdmin (Requested: superadmin / Admin@2025!)
        const superAdminPassword = await bcrypt.hash('Admin@2025!', 10);
        const superAdminId = crypto.randomUUID();
        // User requested identifier 'superadmin'
        const superAdminIdentifier = 'superadmin';

        await pool.query(`
            INSERT INTO core_users (id, tenant_id, name, email, password_hash, status)
            VALUES ($1, $2, $3, $4, $5, 'ACTIVE')
            ON CONFLICT (tenant_id, email) DO UPDATE SET password_hash = EXCLUDED.password_hash
        `, [superAdminId, systemTenantId, 'System Administrator', superAdminIdentifier, superAdminPassword]);

        // Role
        await pool.query(`
            INSERT INTO core_user_roles (user_id, role)
            VALUES ($1, 'superadmin')
            ON CONFLICT (user_id, role) DO NOTHING
        `, [superAdminId]);

        console.log('   ✓ SuperAdmin created (superadmin)');

        // 2. Create Company Admins
        const companyAdmins = [
            // Requested: takeshi_yamamoto / Takeshi@2025 (Company Admin)
            { identifier: 'takeshi_yamamoto', fullName: 'Takeshi Yamamoto', company: 'TechCorp', email: 'takeshi_yamamoto', pass: 'Takeshi@2025', roles: ['admin', 'company'] },
            { identifier: 'kenji', fullName: 'Kenji Tanaka', company: 'AppMakers', email: 'kenji@appmakers.mobile', pass: 'Takeshi@2025', roles: ['admin', 'company'] },
            // Requested: maria_santos / User@2025 (Recruiter) - Placing in DesignHub
            { identifier: 'maria_santos', fullName: 'Maria Santos', company: 'DesignHub', email: 'maria_santos', pass: 'User@2025', roles: ['recruiter', 'company'] }
        ];

        for (const admin of companyAdmins) {
            const hash = await bcrypt.hash(admin.pass, 10);
            const userId = crypto.randomUUID();
            const tenantId = companyMap[admin.company];

            if (!tenantId) {
                console.warn(`Original company ${admin.company} not found for user ${admin.fullName}, skipping.`);
                continue;
            }

            await pool.query(`
                INSERT INTO core_users (id, tenant_id, name, email, password_hash, status)
                VALUES ($1, $2, $3, $4, $5, 'ACTIVE')
                ON CONFLICT (tenant_id, email) DO UPDATE SET password_hash = EXCLUDED.password_hash
            `, [userId, tenantId, admin.fullName, admin.email, hash]);

            for (const role of admin.roles) {
                await pool.query(`
                    INSERT INTO core_user_roles (user_id, role)
                    VALUES ($1, $2)
                    ON CONFLICT (user_id, role) DO NOTHING
                `, [userId, role]);
            }

            console.log(`   ✓ User created: ${admin.email}`);
        }

        // 3. Create Candidates (Job Seekers)
        // Requested: paulo_santos / User@2025
        const candidates = [
            { fullName: 'Paulo Santos', email: 'paulo_santos', pass: 'User@2025' },
            { fullName: 'Maria Reyes', email: 'maria@email.com', pass: 'User@2025' }
        ];

        for (const cand of candidates) {
            const hash = await bcrypt.hash(cand.pass, 10);
            const userId = crypto.randomUUID();

            await pool.query(`
                INSERT INTO core_users (id, tenant_id, name, email, password_hash, status)
                VALUES ($1, $2, $3, $4, $5, 'ACTIVE')
                ON CONFLICT (tenant_id, email) DO UPDATE SET password_hash = EXCLUDED.password_hash
            `, [userId, systemTenantId, cand.fullName, cand.email, hash]);

            await pool.query(`
                INSERT INTO core_user_roles (user_id, role)
                VALUES ($1, 'candidate')
                ON CONFLICT (user_id, role) DO NOTHING
            `, [userId]);
            console.log(`   ✓ Candidate created: ${cand.email}`);
        }

    } catch (error) {
        console.error('   ❌ Error seeding users:', error.message);
        throw error;
    }
}
