"use server";

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

// ─── Create Offer ───
export async function createOffer(
    applicationId: string,
    data: {
        base_salary?: number;
        currency?: string;
        benefits?: string[];
        full_offer_details?: string;
        response_deadline?: string;
    }
) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") {
        return { success: false, error: "Unauthorized" };
    }

    // Verify the application belongs to this employer
    const application = await prisma.application.findUnique({
        where: { id: applicationId },
        include: {
            job: { select: { employer_id: true, title: true, company: true } },
            candidate: { select: { email: true, name: true } },
            offer: true,
        },
    });

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

    if (application.offer) {
        return { success: false, error: "An offer already exists for this application" };
    }

    try {
        const offer = await prisma.applicationOffer.create({
            data: {
                application_id: applicationId,
                base_salary: data.base_salary || undefined,
                currency: data.currency || "NGN",
                benefits: data.benefits ? JSON.stringify(data.benefits) : undefined,
                full_offer_details: data.full_offer_details || undefined,
                response_deadline: data.response_deadline
                    ? new Date(data.response_deadline)
                    : undefined,
                status: "pending",
            },
        });

        // Update application status to offered
        await prisma.application.update({
            where: { id: applicationId },
            data: { status: "offered" },
        });

        await prisma.applicationActivity.create({
            data: {
                application_id: applicationId,
                actor_id: user.id,
                action: "offer_created",
                details: {
                    base_salary: data.base_salary,
                    currency: data.currency || "NGN",
                },
            },
        });

        // Send Email Notification to Candidate
        await EmailService.sendNotificationEmail(
            application.candidate.email,
            `Job Offer: ${application.job.title} at ${application.job.company}`,
            `Hi ${application.candidate.name},<br/><br/>Congratulations! You have received a job offer for the <strong>${application.job.title}</strong> position at <strong>${application.job.company}</strong>.<br/><br/>Please log in to your dashboard to review the offer details and respond by the deadline.`,
            `${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/dashboard/applications/${applicationId}`
        );

        revalidatePath(`/dashboard/applications/${applicationId}`);
        revalidatePath("/dashboard/applications");
        return { success: true, offerId: offer.id };
    } catch (error) {
        console.error("Failed to create offer:", error);
        return { success: false, error: "Failed to create offer." };
    }
}

// ─── Update Offer Status ───
export async function updateOfferStatus(
    offerId: string,
    status: "accepted" | "declined" | "negotiated"
) {
    const user = await getCurrentUser();
    if (!user) {
        return { success: false, error: "Unauthorized" };
    }

    try {
        const offer = await prisma.applicationOffer.findUnique({
            where: { id: offerId },
            include: {
                application: {
                    include: {
                        job: { select: { employer_id: true, title: true, company: true, employer: { select: { email: true, name: true } } } },
                        candidate: { select: { email: true, name: true } }
                    },
                },
            },
        });

        if (!offer) {
            return { success: false, error: "Offer not found" };
        }

        // RBAC: employer can mark any status, candidate can only accept/decline their own
        if (user.role === "candidate") {
            if (offer.application.candidate_id !== user.id) {
                return { success: false, error: "Unauthorized" };
            }
            if (!["accepted", "declined"].includes(status)) {
                return { success: false, error: "Invalid status" };
            }
        } else if (user.role === "employer") {
            if (offer.application.job.employer_id !== user.id) {
                return { success: false, error: "Unauthorized" };
            }
        }

        await prisma.applicationOffer.update({
            where: { id: offerId },
            data: { status },
        });

        // Update application status based on offer outcome
        if (status === "accepted") {
            await prisma.application.update({
                where: { id: offer.application_id },
                data: { status: "hired" },
            });
        }

        // Log activity
        await prisma.applicationActivity.create({
            data: {
                application_id: offer.application_id,
                actor_id: user.id,
                action: `offer_${status}`,
                details: { offerId, by: user.role },
            },
        });

        revalidatePath(`/dashboard/applications/${offer.application_id}`);
        revalidatePath("/dashboard/applications");

        // Notify Employer if Candidate responded
        if (user.role === "candidate") {
            const statusText = status === "accepted" ? "accepted" : status === "declined" ? "declined" : "requested to negotiate";
            await EmailService.sendNotificationEmail(
                offer.application.job.employer.email,
                `Offer ${status.charAt(0).toUpperCase() + status.slice(1)}: ${offer.application.candidate.name}`,
                `Hi ${offer.application.job.employer.name},<br/><br/>The candidate <strong>${offer.application.candidate.name}</strong> has <strong>${statusText}</strong> the job offer for the <strong>${offer.application.job.title}</strong> position.<br/><br/>Please log in to your dashboard to view the details.`,
                `${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/dashboard/applications/${offer.application_id}`
            );
        }

        return { success: true };
    } catch (error) {
        console.error("Failed to update offer status:", error);
        return { success: false, error: "Failed to update offer." };
    }
}
