import { pool, testConnection, closePool } from './db.js';
import { seedRegions } from './seeders/regions.js';
import { seedCities } from './seeders/cities.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';

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

    try {
        // Drop all tables in reverse order (respecting foreign keys)
        await pool.query('DROP TABLE IF EXISTS password_resets CASCADE');
        await pool.query('DROP TABLE IF EXISTS favorite_jobs CASCADE');
        await pool.query('DROP TABLE IF EXISTS applications CASCADE');
        await pool.query('DROP TABLE IF EXISTS jobs CASCADE');
        await pool.query('DROP TABLE IF EXISTS user_companies CASCADE');
        await pool.query('DROP TABLE IF EXISTS companies CASCADE');
        await pool.query('DROP TABLE IF EXISTS users CASCADE');
        await pool.query('DROP TABLE IF EXISTS cities CASCADE');
        await pool.query('DROP TABLE IF EXISTS regions CASCADE');
        await pool.query('DROP TABLE IF EXISTS prefectures CASCADE'); // Legacy drop

        console.log('✅ All tables dropped successfully');
    } 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)
        await seedRegions();
        await seedCities();
        await seedCompanies();
        await seedUsers();
        await seedJobs();
        await seedApplications();

        console.log('\n✅ Database seeding completed successfully!');
        console.log('\n📊 Summary:');
        console.log('   - Regions seeded');
        console.log('   - Cities seeded');
        console.log('   - 1 SuperAdmin');
        console.log('   - 30 Companies');
        console.log('   - 990 Jobs (33 per company)');
        console.log('   - Work modes: onsite, hybrid, remote');
        console.log('   - 20 Applications');

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

// Main execution
const shouldReset = process.argv.includes('--reset');

(async () => {
    if (shouldReset) {
        await resetDatabase();
        console.log('✅ Database reset complete. Run migrations before seeding.');
    } else {
        await seedDatabase();
    }
})();
