"use server";

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

export async function applyForJob(formData: FormData) {
    const user = await getCurrentUser();
    if (!user) return { error: "You must be logged in to apply." };
    if (user.role !== "candidate") return { error: "Only candidates can apply for jobs." };

    const jobId = formData.get("job_id") as string;
    const coverLetter = (formData.get("cover_letter") as string) || null;
    let resumeUrl = formData.get("resume_url") as string;

    if (!jobId) return { error: "Job ID is missing." };

    // Find the job to ensure it's valid
    const job = await prisma.job.findUnique({ where: { id: jobId } });
    if (!job) return { error: "Job not found." };

    // Verify candidate profile has a resume if none was provided in form
    const profile = await prisma.profile.findUnique({ where: { user_id: user.id } });
    
    if (!resumeUrl) {
        if (!profile?.resume_url) {
            return { error: "You must upload a resume to apply." };
        }
        resumeUrl = profile.resume_url;
    }

    try {
        // Create the application
        await prisma.application.create({
            data: {
                job_id: jobId,
                candidate_id: user.id,
                cover_letter: coverLetter,
                resume_url: resumeUrl,
                status: "pending",
                applied_at: new Date(),
            },
        });

        revalidatePath(`/jobs/${jobId}`);
        revalidatePath("/dashboard/applications");
        revalidatePath("/dashboard/employer/applicants");
        
        return { success: true };
    } catch (error: any) {
        // Handle unique constraint failure (already applied)
        if (error.code === 'P2002') {
            return { error: "You have already applied for this job." };
        }
        console.error("Application error:", error);
        return { error: "Failed to submit application. Please try again." };
    }
}

export async function updateApplicationStatus(applicationId: string, status: string) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") {
        return { error: "Unauthorized" };
    }

    try {
        // Verify the employer owns the job related to this application
        const application = await prisma.application.findUnique({
            where: { id: applicationId },
            include: { job: true },
        });

        if (!application || application.job.employer_id !== user.id) {
            return { error: "Application not found or unauthorized." };
        }

        await prisma.application.update({
            where: { id: applicationId },
            data: { status },
        });

        revalidatePath("/dashboard/employer/applicants");
        return { success: true };
    } catch (error) {
        console.error("Failed to update status:", error);
        return { error: "Failed to update application status." };
    }
}
