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' }
];

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 region IDs
    const regions = await pool.query('SELECT id, code FROM regions');
    const regMap = {};
    regions.rows.forEach(r => regMap[r.code] = r.id);
    const defaultRegionId = regMap['13'] || (regions.rows.length > 0 ? regions.rows[0].id : null);

    try {
        for (let i = 0; i < companyData.length; i++) {
            const company = companyData[i];
            const city = cities[i % cities.length];
            const slug = generateSlug(company.name);

            await pool.query(`
                INSERT INTO companies (name, slug, type, document, address, region_id, phone, email, website, description, verified, active)
                VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
                ON CONFLICT (slug) DO UPDATE SET
                    name = EXCLUDED.name,
                    description = EXCLUDED.description,
                    verified = EXCLUDED.verified,
                    active = EXCLUDED.active
            `, [
                company.name,
                slug,
                'company',
                generateCNPJ(i),
                city,
                defaultRegionId,
                `+55-11-${3000 + i}-${String(i).padStart(4, '0')}`,
                `careers@${slug}.com`,
                `https://${slug}.com`,
                JSON.stringify(company.desc),
                true,
                true
            ]);

            // Seed Core Company (One-to-one mapping)
            const coreId = crypto.randomUUID();
            await pool.query(`
                INSERT INTO core_companies (id, name, document, status)
                VALUES ($1, $2, $3, 'ACTIVE')
                ON CONFLICT (id) DO NOTHING
            `, [coreId, company.name, generateCNPJ(i)]);
        }

        // Seed System Tenant for SuperAdmin
        await pool.query(`
            INSERT INTO core_companies (id, name, document, status)
            VALUES ('00000000-0000-0000-0000-000000000000', 'GoHorse System', '00.000.000/0001-91', 'ACTIVE')
            ON CONFLICT (id) DO NOTHING
        `);

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

export { companyData };
