"use server";

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

export async function getEmployerTags() {
    try {
        const user = await getCurrentUser();
        if (!user || user.role !== "employer") {
            return { success: false, error: "Unauthorized" };
        }

        const tags = await prisma.candidateTag.findMany({
            where: { employer_id: user.id },
            orderBy: { name: 'asc' }
        });

        return { success: true, tags };
    } catch (error) {
        console.error("Failed to fetch tags:", error);
        return { success: false, error: "Internal server error" };
    }
}

export async function createEmployerTag(name: string, color: string = "#e2e8f0") {
    try {
        const user = await getCurrentUser();
        if (!user || user.role !== "employer") {
            return { success: false, error: "Unauthorized" };
        }

        const normalizedName = name.trim();
        if (!normalizedName) return { success: false, error: "Tag name required" };

        // Check if already exists
        const existing = await prisma.candidateTag.findUnique({
            where: {
                employer_id_name: {
                    employer_id: user.id,
                    name: normalizedName
                }
            }
        });

        if (existing) {
            return { success: true, tag: existing };
        }

        const tag = await prisma.candidateTag.create({
            data: {
                employer_id: user.id,
                name: normalizedName,
                color
            }
        });

        return { success: true, tag };
    } catch (error) {
        console.error("Failed to create tag:", error);
        return { success: false, error: "Internal server error" };
    }
}

export async function attachTagToApplication(applicationId: string, tagId: string) {
    try {
        const user = await getCurrentUser();
        if (!user || user.role !== "employer") {
            return { success: false, error: "Unauthorized" };
        }

        const application = await prisma.application.findUnique({
            where: { id: applicationId },
            include: { job: true }
        });

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

        // upsert relationship
        await prisma.applicationTag.upsert({
            where: {
                application_id_tag_id: {
                    application_id: applicationId,
                    tag_id: tagId
                }
            },
            update: {},
            create: {
                application_id: applicationId,
                tag_id: tagId
            }
        });

        revalidatePath(`/dashboard/applications/${applicationId}`);
        revalidatePath(`/dashboard/applications`); // To update Kanban
        return { success: true };
    } catch (error) {
        console.error("Failed to attach tag:", error);
        return { success: false, error: "Internal server error" };
    }
}

export async function removeTagFromApplication(applicationId: string, tagId: string) {
    try {
        const user = await getCurrentUser();
        if (!user || user.role !== "employer") {
            return { success: false, error: "Unauthorized" };
        }

        const application = await prisma.application.findUnique({
            where: { id: applicationId },
            include: { job: true }
        });

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

        await prisma.applicationTag.delete({
            where: {
                application_id_tag_id: {
                    application_id: applicationId,
                    tag_id: tagId
                }
            }
        });

        revalidatePath(`/dashboard/applications/${applicationId}`);
        revalidatePath(`/dashboard/applications`);
        return { success: true };
    } catch (error) {
        console.error("Failed to remove tag:", error);
        return { success: false, error: "Internal server error" };
    }
}
