import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';

const prisma = new PrismaClient();

async function main() {
    console.log('Seeding database...');

    // 1. Clean up existing data
    // Order matters due to foreign key constraints
    await prisma.savedJob.deleteMany();
    await prisma.application.deleteMany();
    await prisma.jobSkill.deleteMany();
    await prisma.job.deleteMany();
    await prisma.experience.deleteMany();
    await prisma.education.deleteMany();
    await prisma.userSkill.deleteMany();
    await prisma.profile.deleteMany();
    await prisma.skill.deleteMany();
    await prisma.user.deleteMany();

    console.log('Cleaned up old data.');

    // 2. Create Skills
    const skillsData = [
        { name: 'JavaScript', category: 'Programming' },
        { name: 'TypeScript', category: 'Programming' },
        { name: 'React', category: 'Frontend' },
        { name: 'Next.js', category: 'Frontend' },
        { name: 'Node.js', category: 'Backend' },
        { name: 'PostgreSQL', category: 'Database' },
        { name: 'Prisma', category: 'ORM' },
        { name: 'Python', category: 'Programming' },
        { name: 'Tailwind CSS', category: 'Frontend' },
        { name: 'CSS', category: 'Frontend' },
        { name: 'Docker', category: 'DevOps' },
        { name: 'Cloud Computing', category: 'DevOps' },
    ];

    const skills = [];
    for (const s of skillsData) {
        const skill = await prisma.skill.create({ data: s });
        skills.push(skill);
    }
    console.log(`Created ${skills.length} skills.`);

    const hashedPassword = await bcrypt.hash('password123', 12);
    const adminHashedPassword = await bcrypt.hash('admin123', 12);

    // 3. Create Users
    // Admin
    const admin = await prisma.user.create({
        data: {
            email: 'admin@example.com',
            password_hash: adminHashedPassword,
            role: 'admin',
            name: 'Site Admin',
            first_name: 'System',
            last_name: 'Admin',
            email_verified: new Date(),
        },
    });

    // Employers
    const employer1 = await prisma.user.create({
        data: {
            email: 'techcorp@example.com',
            password_hash: hashedPassword,
            role: 'employer',
            name: 'Tech Corp Recruiting',
            first_name: 'John',
            last_name: 'Employer',
            email_verified: new Date(),
        },
    });

    const employer2 = await prisma.user.create({
        data: {
            email: 'startup@example.com',
            password_hash: hashedPassword,
            role: 'employer',
            name: 'Innovate AI',
            first_name: 'Sarah',
            last_name: 'Founder',
            email_verified: new Date(),
        },
    });

    // Candidates
    const candidate1 = await prisma.user.create({
        data: {
            email: 'candidate1@example.com',
            password_hash: hashedPassword,
            role: 'candidate',
            name: 'Alex Dev',
            first_name: 'Alex',
            last_name: 'Developer',
            email_verified: new Date(),
        },
    });

    const candidate2 = await prisma.user.create({
        data: {
            email: 'candidate2@example.com',
            password_hash: hashedPassword,
            role: 'candidate',
            name: 'Jordan Smith',
            first_name: 'Jordan',
            last_name: 'Smith',
            email_verified: new Date(),
        },
    });

    console.log('Users created.');

    // 4. Create Profiles
    // Employer Profiles
    await prisma.profile.create({
        data: {
            user_id: employer1.id,
            company_name: 'Tech Corp',
            company_website: 'https://techcorp.com',
            company_size: '500-1000',
            location: 'New York, NY',
            company_description: 'Leading technology solutions provider.',
            bio: 'Hiring the best talent in tech.',
        },
    });

    await prisma.profile.create({
        data: {
            user_id: employer2.id,
            company_name: 'Innovate AI',
            company_website: 'https://innovate.ai',
            company_size: '10-50',
            location: 'San Francisco, CA',
            company_description: 'Cutting-edge AI research and development.',
            bio: 'Building the future with AI.',
        },
    });

    // Candidate Profiles
    await prisma.profile.create({
        data: {
            user_id: candidate1.id,
            headline: 'Full Stack Developer',
            bio: 'Experienced developer with 5 years in React and Node.js.',
            location: 'London, UK',
            website_url: 'https://alexdev.me',
            github_url: 'https://github.com/alexdev',
        },
    });

    await prisma.profile.create({
        data: {
            user_id: candidate2.id,
            headline: 'Junior Data Scientist',
            bio: 'Passionate about data analysis and machine learning.',
            location: 'Berlin, Germany',
            linkedin_url: 'https://linkedin.com/in/jordansmith',
        },
    });

    console.log('Profiles created.');

    // 5. Candidate Experience & Education
    await prisma.experience.create({
        data: {
            user_id: candidate1.id,
            title: 'Senior Developer',
            company: 'Web Solutions Ltd',
            location: 'Remote',
            start_date: new Date('2020-01-01'),
            is_current: true,
            description: 'Developing high-scale web applications.',
        },
    });

    await prisma.education.create({
        data: {
            user_id: candidate1.id,
            institution: 'University of Technology',
            degree: 'BSc Computer Science',
            start_date: new Date('2015-09-01'),
            end_date: new Date('2019-06-01'),
        },
    });

    // 6. User Skills
    const reactSkill = skills.find(s => s.name === 'React');
    const nodeSkill = skills.find(s => s.name === 'Node.js');
    const pythonSkill = skills.find(s => s.name === 'Python');

    if (reactSkill) await prisma.userSkill.create({ data: { user_id: candidate1.id, skill_id: reactSkill.id } });
    if (nodeSkill) await prisma.userSkill.create({ data: { user_id: candidate1.id, skill_id: nodeSkill.id } });
    if (pythonSkill) await prisma.userSkill.create({ data: { user_id: candidate2.id, skill_id: pythonSkill.id } });

    // 7. Create Jobs
    // @ts-ignore - slug is valid in schema (Prisma client may need IDE restart)
    const job1 = await prisma.job.create({
        data: {
            employer_id: employer1.id,
            title: 'Frontend Engineer (React)',
            company: 'Tech Corp',
            slug: 'frontend-engineer-react-tech-corp-1',
            city: 'New York',
            state: 'NY',
            work_location_type: 'hybrid',
            type: 'full-time',
            experience_level: 'mid',
            salary_type: 'annual',
            salary_min: 100000,
            salary_max: 150000,
            status: 'published',
            description: '<p>We are looking for a React expert to join our team.</p>',
            responsibilities: ['Write clean code', 'Collaborate with design'],
            required_qualifications: ['3+ years React', 'TypeScript knowledge'],
            application_method: 'internal',
            posted_at: new Date(),
        },
    });

    // @ts-ignore - slug is valid in schema (Prisma client may need IDE restart)
    const job2 = await prisma.job.create({
        data: {
            employer_id: employer2.id,
            title: 'AI Researcher',
            company: 'Innovate AI',
            slug: 'ai-researcher-innovate-ai-2',
            work_location_type: 'remote',
            type: 'full-time',
            experience_level: 'senior',
            salary_type: 'annual',
            salary_min: 120000,
            salary_max: 180000,
            status: 'published',
            description: '<p>Join us to build state of the art LLMs.</p>',
            responsibilities: ['Train AI models', 'Read research papers'],
            required_qualifications: ['PhD in Computer Science', 'PyTorch expertise'],
            application_method: 'internal',
            posted_at: new Date(),
        },
    });

    console.log('Jobs created.');

    // 8. Job Skills
    if (reactSkill) await prisma.jobSkill.create({ data: { job_id: job1.id, skill_id: reactSkill.id } });
    if (pythonSkill) await prisma.jobSkill.create({ data: { job_id: job2.id, skill_id: pythonSkill.id } });

    // 9. Applications
    await prisma.application.create({
        data: {
            job_id: job1.id,
            candidate_id: candidate1.id,
            status: 'reviewing',
            cover_letter: 'I am perfect for this role.',
            years_of_experience: 5,
        },
    });

    await prisma.application.create({
        data: {
            job_id: job2.id,
            candidate_id: candidate2.id,
            status: 'pending',
            cover_letter: 'Interested in AI.',
            years_of_experience: 1,
        },
    });

    console.log('Applications created.');
    console.log('Seeding complete!');
}

main()
    .catch((e) => {
        console.error(e);
        process.exit(1);
    })
    .finally(async () => {
        await prisma.$disconnect();
    });
