"use server";

import { prisma } from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";

export async function getApplicationsForComparison(applicationIds: string[]) {
    try {
        const currentUser = await getCurrentUser();
        if (!currentUser || currentUser.role !== "employer") {
            return { success: false, error: "Unauthorized" };
        }

        if (!applicationIds || applicationIds.length === 0) {
            return { success: false, error: "No applications selected" };
        }

        // Limit to max 4 for UI sanity
        const idsToFetch = applicationIds.slice(0, 4);

        const applications = await prisma.application.findMany({
            where: {
                id: { in: idsToFetch },
                job: { employer_id: currentUser.id } // Security: Ensure employer owns these applications
            },
            include: {
                candidate: {
                    include: {
                        profile: true,
                        experiences: { orderBy: { start_date: 'desc' } },
                        education: { orderBy: { start_date: 'desc' } },
                        skills: { include: { skill: true } }
                    }
                },
                job: {
                    select: {
                        id: true,
                        title: true,
                        skills: { include: { skill: true } },
                        screening_questions: {
                            orderBy: { order: 'asc' }
                        }
                    }
                },
                score: true,
                current_stage: { select: { name: true, color: true } },
                application_tags: { include: { tag: true } }
            }
        });

        // Ensure we preserve the requested order (or just return as is, UI can sort)
        return { success: true, applications };
    } catch (error) {
        console.error("Failed to fetch applications for comparison:", error);
        return { success: false, error: "Internal Server Error" };
    }
}
