"use server";

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

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

        // Verify application and job access
        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 or access denied" };
        }

        // Fetch notes: only public ones, or private ones authored by this user
        const notes = await prisma.candidateNote.findMany({
            where: {
                application_id: applicationId,
                OR: [
                    { is_private: false },
                    { author_id: user.id } // their own private notes
                ]
            },
            include: {
                author: {
                    select: {
                        id: true,
                        name: true,
                        first_name: true,
                        last_name: true,
                        avatar_url: true
                    }
                }
            },
            orderBy: { created_at: 'desc' }
        });

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

export async function createCandidateNote(applicationId: string, content: string, isPrivate: boolean = false) {
    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 or access denied" };
        }

        if (!content.trim()) {
            return { success: false, error: "Note content cannot be empty" };
        }

        const newNote = await prisma.candidateNote.create({
            data: {
                application_id: applicationId,
                author_id: user.id,
                content: content,
                is_private: isPrivate
            },
            include: {
                author: {
                    select: {
                        id: true,
                        name: true,
                        first_name: true,
                        last_name: true,
                        avatar_url: true
                    }
                }
            }
        });

        revalidatePath(`/dashboard/applications/${applicationId}`);

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

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

        const note = await prisma.candidateNote.findUnique({
            where: { id: noteId },
            include: { application: true }
        });

        if (!note || note.author_id !== user.id) {
            return { success: false, error: "Note not found or you don't have permission to delete it" };
        }

        await prisma.candidateNote.delete({
            where: { id: noteId }
        });

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

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