import type { Profile, Skill, Experience, Education } from "@prisma/client";

type ProfileWithRelations = Profile & {
    user?: {
        skills?: { skill: Skill }[];
        experiences?: Experience[];
        education?: Education[];
        avatar_url?: string | null;
    };
};

export type CompletionResult = {
    score: number; // 0-100
    missing: string[];
    tips: { label: string; done: boolean }[];
};

// ─────────────────────────────────────────────────────────────────────────────
// CANDIDATE completion
// ─────────────────────────────────────────────────────────────────────────────
export function calculateCandidateCompletion(profile: ProfileWithRelations | null, skillCount: number, experienceCount: number, educationCount: number, hasAvatar: boolean): CompletionResult {
    const tips = [
        { label: "Add a professional headline", done: !!profile?.headline },
        { label: "Set your location", done: !!profile?.location },
        { label: "Write a bio", done: !!profile?.bio && (profile.bio?.length ?? 0) > 20 },
        { label: "Add at least 3 skills", done: skillCount >= 3 },
        { label: "Add work experience", done: experienceCount >= 1 },
        { label: "Add education", done: educationCount >= 1 },
        { label: "Upload your resume", done: !!profile?.resume_url },
        { label: "Upload a profile photo", done: hasAvatar },
    ];

    const weights = [15, 10, 10, 20, 20, 10, 10, 5];
    const score = tips.reduce((acc, tip, i) => acc + (tip.done ? weights[i] : 0), 0);
    const missing = tips.filter((t) => !t.done).map((t) => t.label);

    return { score: Math.min(score, 100), missing, tips };
}

// ─────────────────────────────────────────────────────────────────────────────
// EMPLOYER completion
// ─────────────────────────────────────────────────────────────────────────────
export function calculateEmployerCompletion(profile: Profile | null, hasLogo: boolean): CompletionResult {
    const tips = [
        { label: "Add company name", done: !!profile?.company_name },
        { label: "Add company website", done: !!profile?.company_website },
        { label: "Set company location", done: !!profile?.company_location },
        { label: "Select industry", done: !!profile?.company_industry },
        { label: "Set company size", done: !!profile?.company_size },
        { label: "Write company description", done: !!profile?.company_description && (profile.company_description?.length ?? 0) > 20 },
        { label: "Upload company logo", done: hasLogo },
    ];

    const weights = [20, 10, 10, 15, 10, 20, 15];
    const score = tips.reduce((acc, tip, i) => acc + (tip.done ? weights[i] : 0), 0);
    const missing = tips.filter((t) => !t.done).map((t) => t.label);

    return { score: Math.min(score, 100), missing, tips };
}
