import prisma from '@/lib/prisma';
import type { Job, User } from '@/lib/db';

/**
 * Calculate match score between user skills and job skills
 */
function calculateMatchScore(userSkills: string[], jobSkills: string[]): number {
    if (jobSkills.length === 0) return 0;

    const normalizedUserSkills = userSkills.map(s => s.toLowerCase().trim());
    const matchingSkills = jobSkills.filter(skill =>
        normalizedUserSkills.includes(skill.toLowerCase().trim())
    );

    return Math.round((matchingSkills.length / jobSkills.length) * 100);
}

/**
 * Get recommended jobs for a user based on skill matching
 */
export async function getRecommendedJobs(user: User): Promise<(Job & { matchScore: number; matchReasons: string[] })[]> {
    if (!user.skills || user.skills.length === 0) return [];

    // Fetch user profile for location matching
    const profile = await prisma.profile.findUnique({
        where: { user_id: user.id },
        select: { location: true }
    });

    const rawJobs = await prisma.job.findMany({
        where: { status: 'published' },
        include: {
            skills: { include: { skill: true } }
        },
        orderBy: { posted_at: 'desc' }
    });

    const jobs = rawJobs.map(j => {
        const jobSkills = j.skills.map(js => js.skill.name);
        const skillScore = calculateMatchScore(user.skills as string[], jobSkills);

        let matchScore = skillScore;
        const matchReasons: string[] = [];

        if (skillScore >= 70) {
            matchReasons.push("Strong skills match");
        } else if (skillScore > 0) {
            matchReasons.push("Partial skills match");
        }

        const jobLocation = `${j.city || ''} ${j.state || ''}`.trim() || j.work_location_type || '';

        if (profile?.location && jobLocation &&
            (jobLocation.toLowerCase().includes(profile.location.toLowerCase()) ||
                profile.location.toLowerCase().includes(jobLocation.toLowerCase()))) {
            matchScore = Math.min(100, matchScore + 15);
            matchReasons.push("Location match");
        }

        // Add novelty boost for very recent jobs (last 3 days)
        if (Date.now() - j.posted_at.getTime() < 3 * 24 * 60 * 60 * 1000) {
            matchScore = Math.min(100, matchScore + 5);
        }

        return {
            id: j.id,
            title: j.title,
            company: j.company,
            location: jobLocation,
            type: j.type,
            salaryMin: j.salary_min || undefined,
            salaryMax: j.salary_max || undefined,
            postedAt: j.posted_at.toISOString(),
            description: j.description || undefined,
            skills: jobSkills,
            applicants: j.applicant_count,
            featured: j.is_featured,
            employerId: j.employer_id,
            status: j.status as 'draft' | 'published' | 'expired' | 'archived',
            matchScore,
            matchReasons,
        };
    });

    return jobs
        .filter(j => j.matchScore > 0)
        .sort((a, b) => b.matchScore - a.matchScore);
}
