"use server";

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

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

    if (!jobId || !candidateId) {
        return { success: false, error: "Missing required fields" };
    }

    try {
        // Check if already applied
        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,
            }
        });

        // Increment applicant count on the job
        await prisma.job.update({
            where: { id: jobId },
            data: { applicant_count: { increment: 1 } }
        });

        // --- EMAIL NOTIFICATION: Candidate Confirmation ---
        try {
            const jobData = await prisma.job.findUnique({
                where: { id: jobId },
                select: { title: true, company: true }
            });
            const candidateData = await prisma.user.findUnique({
                where: { id: candidateId },
                select: { email: true, name: true, first_name: true, last_name: true }
            });

            if (candidateData?.email && jobData) {
                const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
                await EmailQueueService.enqueueEmail(
                    'candidate_application_received',
                    candidateData.email,
                    {
                        candidateName: candidateData.name || `${candidateData.first_name || ''} ${candidateData.last_name || ''}`.trim() || 'Candidate',
                        jobTitle: jobData.title,
                        companyName: jobData.company || 'the employer',
                        applicationId: application.id,
                        statusUrl: `${baseUrl}/dashboard/candidate/applications/${application.id}`
                    },
                    candidateId
                );
            }
        } catch (emailErr) {
            console.error("Failed to enqueue application confirmation email:", emailErr);
        }

        revalidatePath("/");
        revalidatePath("/dashboard");
        return { success: true, applicationId: application.id };
    } catch (error) {
        console.error("Failed to apply:", error);
        return { success: false, error: "Failed to submit application. Please try again." };
    }
}

export async function updateApplicationStatus(
    id: string,
    status: "pending" | "reviewing" | "interview" | "rejected" | "accepted" | "withdrawn" | "offered"
) {
    try {
        const application = await prisma.application.update({
            where: { id },
            data: { status },
            include: {
                candidate: { select: { email: true } },
                job: { select: { title: true } }
            }
        });

        // Notify Candidate of status change
        if (["reviewing", "interview", "rejected", "offered", "accepted"].includes(status)) {
            const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
            const templateType = status === 'rejected'
                ? 'candidate_application_rejected'
                : 'candidate_application_status_update';

            await EmailQueueService.enqueueEmail(
                templateType,
                application.candidate.email,
                {
                    candidateName: (application.candidate as any).name || (application.candidate as any).first_name || 'Candidate',
                    jobTitle: application.job.title,
                    companyName: (application.job as any).company || 'the employer',
                    newStatus: status.charAt(0).toUpperCase() + status.slice(1),
                    statusUrl: `${baseUrl}/dashboard/candidate/applications/${application.id}`
                },
                application.candidate_id
            );
        }

        revalidatePath("/dashboard");
        revalidatePath("/dashboard/applications");
    } catch (error) {
        console.error("Failed to update application status:", error);
    }
}
