import { fileURLToPath } from 'node:url';
import { pool, testConnection, closePool } from './db.js';
import { seedBaseLocations, seedDetailedLocations, seedLocationDataLite } from './seeders/location-loader.js';
import { seedUsers } from './seeders/users.js';
import { seedCompanies } from './seeders/companies.js';
import { seedJobs } from './seeders/jobs.js';
import { seedApplications } from './seeders/applications.js';
import { seedAcmeCorp, seedWileECoyote } from './seeders/acme.js';
import { seedFictionalCompanies } from './seeders/fictional-companies.js';
import { seedEpicCompanies } from './seeders/epic-companies.js';
import { seedNotifications } from './seeders/notifications.js';
import { seedTags } from './seeders/tags.js';
import { seedTickets } from './seeders/tickets.js';

async function resetDatabase() {
    console.log('🗑️  Resetting database...');

    try {
        // Dynamic drop: Fetch all tables in public schema and drop them
        // This avoids "must be owner of schema public" error by operating on tables directly
        console.log('🔍 Finding tables to drop...');
        const tablesResult = await pool.query(`
            SELECT tablename 
            FROM pg_tables 
            WHERE schemaname = 'public'
        `);

        if (tablesResult.rows.length > 0) {
            const tables = tablesResult.rows.map(row => row.tablename);
            console.log(`🔥 Dropping ${tables.length} tables: ${tables.join(', ')}`);

            // Construct a single DROP statement for all tables (CASCADE handles dependencies)
            const tableList = tables.map(t => `"${t}"`).join(', ');
            await pool.query(`DROP TABLE IF EXISTS ${tableList} CASCADE`);
            console.log('✅ All public tables dropped successfully.');
        } else {
            console.log('ℹ️  No tables found to drop IN public schema.');
        }
    } catch (error) {
        console.error('❌ Error resetting database:', error.message);
        throw error;
    }
}

async function runMigrations() {
    console.log('📦 Running migrations...');

    // This would typically read from migration files
    // For now, we'll just log that migrations should be run separately
    const host = process.env.DB_HOST || '172.28.22.171';
    const user = process.env.DB_USER || 'usuario';
    const db = process.env.DB_NAME || 'todaijobs';
    console.log(`ℹ️  Run migrations via: psql -h ${host} -U ${user} -d ${db} -f migrations/*.sql`);
}

async function seedDatabase() {
    console.log('🌱 Starting database seeding...\n');

    try {
        // Test connection first
        const connected = await testConnection();
        if (!connected) {
            throw new Error('Could not connect to database');
        }

        console.log('');

        // Seed in order (respecting foreign key dependencies)
        // 1. Base Location data (Continents, Countries) - Fast & Required for Companies
        console.time('🌍 Base Location Seeding');
        await seedBaseLocations();
        console.timeEnd('🌍 Base Location Seeding');

        // 2. Then companies (need countries)
        await seedCompanies();

        // 3. Then users (need companies)
        await seedUsers();

        // 4. Detailed Location data (States, Cities) - Heavy
        console.time('🌍 Detailed Location Seeding');
        await seedDetailedLocations();
        console.timeEnd('🌍 Detailed Location Seeding');

        // 5. Jobs & Applications (need users & companies)
        await seedJobs();
        await seedAcmeCorp(); // 🏭 ACME Corp + 69 vagas hilariantes
        await seedWileECoyote(); // 🐺 Wile E. Coyote user
        await seedFictionalCompanies(); // 🎬 Stark Industries, Los Pollos, Springfield Nuclear
        await seedEpicCompanies(); // 🌟 BNL, Cyberdyne, Wonka, Wayne, Oceanic, InGen, Bubba Gump, Umbrella, Sprawl-Mart
        await seedApplications(); // 📝 Applications from candidates
        await seedNotifications(); // 🔔 Notifications for dashboard
        await seedTickets(); // 🎫 Support tickets
        await seedTags(); // 🏷️ Job tags (area, level, stack)

        console.log('\n✅ Database seeding completed successfully!');
        console.log('\n📊 Summary:');
        console.log('   - 🌍 Location data (continents, subregions, countries, states, cities)');
        console.log('   - 1 SuperAdmin');
        console.log('   - 43 Companies (30 + 13 fictícias)');
        console.log('   - 1129+ Jobs total');
        console.log('   - 🏭 ACME Corp: 69 vagas Looney Tunes');
        console.log('   - 🦸 Stark Industries: 8 vagas Marvel');
        console.log('   - 🐔 Los Pollos Hermanos: 4 vagas Breaking Bad');
        console.log('   - ☢️ Springfield Nuclear: 4 vagas Simpsons');
        console.log('   - 🛏️ Buy n Large: 3 vagas Wall-E');
        console.log('   - 🤖 Cyberdyne Systems: 3 vagas Terminator');
        console.log('   - 🍫 Wonka Industries: 3 vagas Chocolate Factory');
        console.log('   - 🦇 Wayne Enterprises: 3 vagas Batman');
        console.log('   - ✈️ Oceanic Airlines: 3 vagas Lost');
        console.log('   - 🦖 InGen Jurassic Park: 3 vagas Jurassic Park');
        console.log('   - 🦐 Bubba Gump Shrimp: 3 vagas Forrest Gump');
        console.log('   - ☣️ Umbrella Corporation: 3 vagas Resident Evil');
        console.log('   - 🏪 Sprawl-Mart: 30 vagas Dystopia');
        console.log('   - 🐺 Wile E. Coyote: wile_e_coyote / MeepMeep@123');
        console.log('   - Work modes: onsite, hybrid, remote');
        console.log('   - 20 Applications');

    } catch (error) {
        console.error('\n❌ Seeding failed:', error.message);
        console.error(error);
        throw error;
    }
    // Do NOT close pool here
}

// Lite version (skips cities for faster seeding)
async function seedDatabaseLite() {
    console.log('🌱 Starting database seeding (LITE - no cities)...\n');
    console.log('🔍 Debug: seedDatabaseLite started');
    console.log('🌶️  PASSWORD_PEPPER:', process.env.PASSWORD_PEPPER ? `"${process.env.PASSWORD_PEPPER}"` : '(not set)');

    try {
        const connected = await testConnection();
        if (!connected) {
            throw new Error('Could not connect to database');
        }

        console.log('');

        // Seed in order (respecting foreign key dependencies)
        console.log('🔍 Debug: seeding location data (lite)...');
        await seedLocationDataLite(); // ⚡ Fast mode - no cities
        console.log('🔍 Debug: seeding companies...');
        await seedCompanies();
        console.log('🔍 Debug: seeding users...');
        await seedUsers();
        console.log('🔍 Debug: seeding jobs...');
        await seedJobs();
        await seedAcmeCorp();
        await seedWileECoyote();
        await seedFictionalCompanies();
        await seedEpicCompanies();
        await seedApplications();
        await seedNotifications();
        await seedTickets();
        await seedTags();

        console.log('\n✅ Database seeding (LITE) completed successfully!');
        console.log('🔍 Debug: seedDatabaseLite finished normally');
        console.log('   ⚡ Cities skipped for faster seeding');

    } catch (error) {
        console.error('\n❌ Seeding failed:', error.message);
        console.error(error);
        throw error;
    }
}

// Ultra-fast version (skips ALL location data)
async function seedDatabaseNoLocations() {
    console.log('🌱 Starting database seeding (NO LOCATIONS)...\n');
    console.log('🌶️  PASSWORD_PEPPER:', process.env.PASSWORD_PEPPER ? `"${process.env.PASSWORD_PEPPER}"` : '(not set)');
    console.log('⏭️  Skipping ALL location data (continents, countries, states, cities)\n');

    try {
        const connected = await testConnection();
        if (!connected) {
            throw new Error('Could not connect to database');
        }

        console.log('');

        // Skip location data entirely - just seed business data
        await seedCompanies();
        await seedUsers();
        await seedJobs();
        await seedAcmeCorp();
        await seedWileECoyote();
        await seedFictionalCompanies();
        await seedEpicCompanies();
        await seedApplications();
        await seedNotifications();
        await seedTags();

        console.log('\n✅ Database seeding (NO LOCATIONS) completed successfully!');
        console.log('   ⏭️  All location data skipped (continents, countries, states, cities)');

    } catch (error) {
        console.error('\n❌ Seeding failed:', error.message);
        console.error(error);
        throw error;
    }
}

// Main execution
export {
    resetDatabase,
    seedDatabase,
    seedDatabaseLite,
    seedDatabaseNoLocations
};

// Check if run directly
if (process.argv[1] === fileURLToPath(import.meta.url)) {
    const shouldReset = process.argv.includes('--reset');
    const shouldLite = process.argv.includes('--lite');
    const shouldSkipLocations = process.argv.includes('--skip-locations');

    (async () => {
        try {
            if (shouldReset) {
                await resetDatabase();
                console.log('✅ Database reset complete. Run migrations before seeding.');
            } else if (shouldSkipLocations) {
                await seedDatabaseNoLocations();
            } else if (shouldLite) {
                await seedDatabaseLite();
            } else {
                await seedDatabase();
            }
        } catch (error) {
            console.error('❌ Execution failed:', error);
            process.exit(1);
        } finally {
            await import('./db.js').then(m => m.closePool());
        }
    })();
}
