"use server";

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

export async function quickApplyToJob(jobId: string, candidateId: string) {
    // Check profile completeness
    const profile = await prisma.profile.findUnique({
        where: { user_id: candidateId }
    });

    if (!profile || (!profile.resume_url && !profile.linkedin_url)) {
        return { success: false, error: "Please complete your profile or upload a resume before using Quick Apply." };
    }

    try {
        const existing = await prisma.application.findUnique({
            where: {
                job_id_candidate_id: { job_id: jobId, candidate_id: candidateId }
            }
        });

        if (existing) {
            return { success: false, error: "You have already applied to this job." };
        }

        const application = await prisma.application.create({
            data: {
                job_id: jobId,
                candidate_id: candidateId,
                status: "pending",
                notes: "Submitted via Quick Apply",
                match_score: Math.round(Math.random() * 20 + 80), // 80-100 placeholder for Quick Apply
            }
        });

        // Track Activity
        await prisma.applicationActivity.create({
            data: {
                application_id: application.id,
                action: "submitted",
                actor_id: candidateId,
                details: { method: "Quick Apply" }
            }
        });

        await prisma.job.update({
            where: { id: jobId },
            data: { applicant_count: { increment: 1 } }
        });

        revalidatePath("/");
        revalidatePath("/dashboard");
        revalidatePath(`/jobs/${jobId}`);
        return { success: true, applicationId: application.id };
    } catch (error) {
        console.error("Quick apply failed:", error);
        return { success: false, error: "Failed to submit Quick Apply." };
    }
}

export async function submitStandardApplication(formData: FormData) {
    const jobId = formData.get("jobId") as string;
    const candidateId = formData.get("candidateId") as string;

    // Process screening questions 
    const answersRaw = formData.get("answers") as string;
    let answers = null;
    if (answersRaw) {
        try { answers = JSON.parse(answersRaw); } catch (e) { console.error("Answers parse error", e); }
    }

    try {
        const existing = await prisma.application.findUnique({
            where: {
                job_id_candidate_id: { job_id: jobId, candidate_id: candidateId }
            }
        });

        if (existing) {
            return { success: false, error: "You have already applied to this job" };
        }

        const application = await prisma.application.create({
            data: {
                job_id: jobId,
                candidate_id: candidateId,
                cover_letter: formData.get("coverLetter") as string || undefined,
                cv_link: formData.get("cvLink") as string || undefined,
                years_of_experience: formData.get("yearsOfExperience") ? Number(formData.get("yearsOfExperience")) : undefined,
                answers,
                match_score: Math.round(Math.random() * 40 + 60), // mock
            }
        });

        await prisma.job.update({
            where: { id: jobId },
            data: { applicant_count: { increment: 1 } }
        });

        await prisma.applicationActivity.create({
            data: {
                application_id: application.id,
                action: "submitted",
                actor_id: candidateId,
                details: { method: "Standard Application Form" }
            }
        });

        revalidatePath("/dashboard/applications");
        return { success: true, applicationId: application.id };
    } catch (error) {
        console.error("Application submission failed:", error);
        return { success: false, error: "Failed to submit application." };
    }
}

export async function withdrawApplication(applicationId: string, reason?: string) {
    try {
        const application = await prisma.application.update({
            where: { id: applicationId },
            data: {
                is_withdrawn: true,
                status: "withdrawn",
                notes: reason ? `Withdrawn: ${reason}` : "Withdrawn by candidate"
            }
        });

        await prisma.applicationActivity.create({
            data: {
                application_id: applicationId,
                action: "withdrawn",
                actor_id: application.candidate_id,
                details: { reason }
            }
        });

        revalidatePath("/dashboard/applications");
        return { success: true };
    } catch (err) {
        console.error("Withdrawal error:", err);
        return { success: false, error: "Failed to withdraw application." };
    }
}
