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

export async function seedJobs() {
    console.log('💼 Seeding jobs...');

    // Get company IDs
    const companiesRes = await pool.query('SELECT id, name FROM companies ORDER BY id');
    const companies = companiesRes.rows;
    const getCompany = (name) => companies.find(c => c.name === name) || companies[0];

    // Get a user ID for created_by (use first core_user or fallback)
    const usersRes = await pool.query('SELECT id FROM core_users LIMIT 1');
    const createdById = usersRes.rows.length > 0 ? 1 : 1; // Legacy integer ID fallback

    // Actually, jobs.created_by references users(id) which is SERIAL (integer)
    // We need to insert into legacy users table first OR skip created_by
    // For now, let's insert a placeholder user into legacy users table
    await pool.query(`
        INSERT INTO users (identifier, password_hash, role, full_name)
        VALUES ('system_seed', '$2b$10$placeholder', 'superadmin', 'System Seeder')
        ON CONFLICT (identifier) DO NOTHING
    `);
    const seedUserRes = await pool.query("SELECT id FROM users WHERE identifier = 'system_seed'");
    const seedUserId = seedUserRes.rows[0]?.id || 1;

    const jobs = [
        {
            companyId: getCompany('TechCorp').id,
            createdBy: seedUserId,
            title: 'Desenvolvedor Full Stack Sênior',
            description: 'Buscamos um desenvolvedor full stack experiente para liderar projetos críticos. Domínio de React, Node.js e arquitetura de microsserviços é essencial.',
            salaryMin: 12000, salaryMax: 18000, salaryType: 'monthly',
            employmentType: 'full-time', workingHours: '9:00-18:00',
            location: 'São Paulo - SP',
            requirements: JSON.stringify(['React', 'Node.js', 'TypeScript', 'Docker', 'AWS']),
            benefits: JSON.stringify(['Plano de Saúde', 'Vale Refeição', 'Gympass', 'PLR']),
            visaSupport: false, languageLevel: 'native', status: 'open'
        },
        {
            companyId: getCompany('DesignHub').id,
            createdBy: seedUserId,
            title: 'Designer UX/UI',
            description: 'Procuramos designer criativo para criar experiências incríveis.',
            salaryMin: 8000, salaryMax: 12000, salaryType: 'monthly',
            employmentType: 'full-time', workingHours: 'Flexível',
            location: 'São Paulo - SP (Remoto)',
            requirements: JSON.stringify(['Figma', 'Adobe XD', 'Portfolio forte']),
            benefits: JSON.stringify(['Trabalho 100% Remoto', 'MacBook Pro']),
            visaSupport: false, languageLevel: 'native', status: 'open'
        },
        {
            companyId: getCompany('DataFlow').id,
            createdBy: seedUserId,
            title: 'Engenheiro de Dados',
            description: 'Oportunidade para trabalhar com big data e machine learning.',
            salaryMin: 15000, salaryMax: 22000, salaryType: 'monthly',
            employmentType: 'full-time', workingHours: '9:00-18:00',
            location: 'Rio de Janeiro - RJ',
            requirements: JSON.stringify(['Python', 'SQL', 'Spark', 'Airflow']),
            benefits: JSON.stringify(['Plano de Saúde Top', 'Vale Alimentação']),
            visaSupport: false, languageLevel: 'native', status: 'open'
        },
        {
            companyId: getCompany('InnovateLab').id,
            createdBy: seedUserId,
            title: 'Product Manager',
            description: 'Lidere o desenvolvimento de produtos digitais inovadores.',
            salaryMin: 10000, salaryMax: 16000, salaryType: 'monthly',
            employmentType: 'full-time', workingHours: '9:00-18:00',
            location: 'Belo Horizonte - MG',
            requirements: JSON.stringify(['Gestão de produtos', 'Agile']),
            benefits: JSON.stringify(['Stock Options', 'Ambiente descontraído']),
            visaSupport: false, languageLevel: 'native', status: 'open'
        },
        {
            companyId: getCompany('AppMakers').id,
            createdBy: seedUserId,
            title: 'Desenvolvedor Mobile',
            description: 'Desenvolva aplicativos mobile de alta qualidade.',
            salaryMin: 9000, salaryMax: 14000, salaryType: 'monthly',
            employmentType: 'full-time', workingHours: 'Flexível',
            location: 'São Paulo - SP',
            requirements: JSON.stringify(['React Native', 'iOS', 'Android']),
            benefits: JSON.stringify(['Remoto', 'Horário Flexível']),
            visaSupport: false, languageLevel: 'native', status: 'open'
        },
        {
            companyId: getCompany('CloudTech').id,
            createdBy: seedUserId,
            title: 'DevOps Engineer',
            description: 'Gerencie infraestrutura cloud e pipelines de CI/CD.',
            salaryMin: 13000, salaryMax: 19000, salaryType: 'monthly',
            employmentType: 'full-time', workingHours: '9:00-18:00',
            location: 'São Paulo - SP',
            requirements: JSON.stringify(['Docker', 'Kubernetes', 'AWS', 'Terraform']),
            benefits: JSON.stringify(['Certificações pagas', 'Plano de Saúde']),
            visaSupport: false, languageLevel: 'native', status: 'open'
        }
    ];

    try {
        for (const job of jobs) {
            await pool.query(`
                INSERT INTO jobs (company_id, created_by, title, description, 
                    salary_min, salary_max, salary_type, employment_type, working_hours,
                    location, requirements, benefits, visa_support, language_level, status)
                VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
            `, [
                job.companyId, job.createdBy, job.title, job.description,
                job.salaryMin, job.salaryMax, job.salaryType, job.employmentType, job.workingHours,
                job.location, job.requirements, job.benefits, job.visaSupport, job.languageLevel, job.status
            ]);
        }

        console.log(`   ✓ ${jobs.length} jobs seeded`);
    } catch (error) {
        console.error('   ❌ Error seeding jobs:', error.message);
        throw error;
    }
}

