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

// 30 realistic tech company names
const companyData = [
    { name: 'TechCorp', desc: 'Enterprise software solutions' },
    { name: 'DesignHub', desc: 'UI/UX and branding agency' },
    { name: 'DataFlow', desc: 'Big data and analytics' },
    { name: 'InnovateLab', desc: 'Innovation and product development' },
    { name: 'AppMakers', desc: 'Mobile app development' },
    { name: 'CloudTech', desc: 'Cloud infrastructure and DevOps' },
    { name: 'CyberShield', desc: 'Cybersecurity solutions' },
    { name: 'PixelPerfect', desc: 'Digital design studio' },
    { name: 'CodeNinja', desc: 'Custom software development' },
    { name: 'AIVentures', desc: 'Artificial intelligence research' },
    { name: 'FinTechPro', desc: 'Financial technology solutions' },
    { name: 'HealthTech', desc: 'Healthcare technology' },
    { name: 'EduSmart', desc: 'Educational technology platform' },
    { name: 'GreenCode', desc: 'Sustainable tech solutions' },
    { name: 'RoboLogic', desc: 'Robotics and automation' },
    { name: 'BlockChainX', desc: 'Blockchain development' },
    { name: 'GameForge', desc: 'Game development studio' },
    { name: 'StreamLive', desc: 'Streaming technology' },
    { name: 'E-CommerceHub', desc: 'E-commerce solutions' },
    { name: 'LogiTech', desc: 'Logistics technology' },
    { name: 'SpaceTech', desc: 'Aerospace software' },
    { name: 'BioInformatics', desc: 'Bioinformatics and research' },
    { name: 'VRWorld', desc: 'Virtual reality experiences' },
    { name: 'IoTConnect', desc: 'Internet of Things solutions' },
    { name: 'QuantumBits', desc: 'Quantum computing research' },
    { name: 'AgriTech', desc: 'Agricultural technology' },
    { name: 'MediaForge', desc: 'Digital media production' },
    { name: 'TravelTech', desc: 'Travel technology platform' },
    { name: 'PropTech', desc: 'Real estate technology' },
    { name: 'SocialHub', desc: 'Social media technology' },
    { name: 'ACME Corporation', desc: 'Innovation in Failure' }
];

const cities = [
    'São Paulo - SP', 'Rio de Janeiro - RJ', 'Belo Horizonte - MG',
    'Curitiba - PR', 'Porto Alegre - RS', 'Brasília - DF',
    'Salvador - BA', 'Recife - PE', 'Fortaleza - CE', 'Campinas - SP'
];

function generateSlug(name) {
    return name.toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/-+/g, '-');
}

function generateCNPJ(index) {
    const base = String(index + 10).padStart(2, '0');
    return `${base}.${base}${base}.${base}${base}/0001-${base}`;
}

export async function seedCompanies() {
    console.log('🏢 Seeding 30 companies...');

    // Get Brazil's country ID from new countries table
    const countryResult = await pool.query("SELECT id FROM countries WHERE iso2 = 'BR'");
    const brazilId = countryResult.rows[0]?.id || null;

    const employeeCounts = ['1-10', '11-50', '51-200', '201-500', '501-1000', '1001+'];

    try {
        for (let i = 0; i < companyData.length; i++) {
            const company = companyData[i];
            const city = cities[i % cities.length];
            const slug = generateSlug(company.name);
            const employeeCount = employeeCounts[i % employeeCounts.length];
            const foundedYear = 1990 + (i % 34); // Random year between 1990 and 2024

            await pool.query(`
                INSERT INTO companies (name, slug, type, document, address, country_id, phone, email, website, description, employee_count, founded_year, verified, active)
                VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
                ON CONFLICT (slug) DO UPDATE SET
                    name = EXCLUDED.name,
                    description = EXCLUDED.description,
                    employee_count = EXCLUDED.employee_count,
                    founded_year = EXCLUDED.founded_year,
                    website = EXCLUDED.website,
                    verified = EXCLUDED.verified,
                    active = EXCLUDED.active
            `, [
                company.name,
                slug,
                'company',
                generateCNPJ(i),
                city,
                brazilId,
                `+55${11 + (i % 20)}9${String(i).padStart(4, '0')}1234`, // Randomized phone
                `careers@${slug}.com`,
                `https://www.${slug}.com`,
                JSON.stringify(company.desc), // Keeping as is, but maybe wrap in HTML p tag? No, existing code used this.
                employeeCount,
                foundedYear,
                true,
                true
            ]);

        }

        // Seed System Company for SuperAdmin
        await pool.query(`
            INSERT INTO companies (name, slug, type, document, email, description, verified, active)
            VALUES ('GoHorse System', 'gohorse-system', 'system', '00.000.000/0001-91', 'admin@gohorsejobs.com', '{"tagline": "System Administration"}', true, true)
            ON CONFLICT (slug) DO NOTHING
        `);

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

export { companyData };
