"use server";

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

// ─── Team Member Roles ──────────────────────────────────
const VALID_ROLES = ["recruiter", "hiring_manager", "interviewer", "hr_admin", "executive"] as const;
type TeamRole = (typeof VALID_ROLES)[number];

// ─── Get Hiring Team ────────────────────────────────────
export async function getHiringTeam(jobId: string) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    const members = await prisma.hiringTeamMember.findMany({
        where: { job_id: jobId, job: { employer_id: user.id } },
        include: {
            user: {
                select: { id: true, name: true, email: true, avatar_url: true, role: true },
            },
        },
        orderBy: { invited_at: "asc" },
    });

    return { success: true, members };
}

// ─── Add Team Member ────────────────────────────────────
export async function addTeamMember(jobId: string, userId: string, role: string) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };
    if (!VALID_ROLES.includes(role as TeamRole)) return { success: false, error: "Invalid role" };

    // Verify job belongs to employer
    const job = await prisma.job.findUnique({ where: { id: jobId } });
    if (!job || job.employer_id !== user.id) return { success: false, error: "Job not found" };

    // Verify target user exists
    const targetUser = await prisma.user.findUnique({ where: { id: userId } });
    if (!targetUser) return { success: false, error: "User not found" };

    try {
        const member = await prisma.hiringTeamMember.upsert({
            where: { job_id_user_id: { job_id: jobId, user_id: userId } },
            create: { job_id: jobId, user_id: userId, role, invited_at: new Date() },
            update: { role, is_active: true },
            include: { user: { select: { id: true, name: true, email: true, avatar_url: true } } },
        });

        // Create notification for the added user
        await prisma.notification.create({
            data: {
                user_id: userId,
                type: "team_invite",
                title: `You've been added to a hiring team`,
                message: `You've been added as ${role.replace("_", " ")} for "${job.title}"`,
                link: `/dashboard/ats`,
            },
        });

        revalidatePath("/dashboard/ats");
        return { success: true, member };
    } catch (error) {
        console.error("Add team member error:", error);
        return { success: false, error: "Failed to add team member" };
    }
}

// ─── Remove Team Member ─────────────────────────────────
export async function removeTeamMember(jobId: string, userId: string) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    const job = await prisma.job.findUnique({ where: { id: jobId } });
    if (!job || job.employer_id !== user.id) return { success: false, error: "Job not found" };

    await prisma.hiringTeamMember.deleteMany({
        where: { job_id: jobId, user_id: userId },
    });

    revalidatePath("/dashboard/ats");
    return { success: true };
}

// ─── Update Team Member Role ────────────────────────────
export async function updateTeamMemberRole(jobId: string, userId: string, role: string) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };
    if (!VALID_ROLES.includes(role as TeamRole)) return { success: false, error: "Invalid role" };

    const job = await prisma.job.findUnique({ where: { id: jobId } });
    if (!job || job.employer_id !== user.id) return { success: false, error: "Job not found" };

    await prisma.hiringTeamMember.updateMany({
        where: { job_id: jobId, user_id: userId },
        data: { role },
    });

    revalidatePath("/dashboard/ats");
    return { success: true };
}

// ─── Search Users for Team ──────────────────────────────
export async function searchTeamCandidates(query: string) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    if (!query.trim() || query.length < 2) return { success: true, users: [] };

    const users = await prisma.user.findMany({
        where: {
            OR: [
                { name: { contains: query, mode: "insensitive" } },
                { email: { contains: query, mode: "insensitive" } },
            ],
            id: { not: user.id }, // exclude self
        },
        select: { id: true, name: true, email: true, avatar_url: true, role: true },
        take: 10,
    });

    return { success: true, users };
}

// ─── Team Comments ──────────────────────────────────────

export async function addTeamComment(
    applicationId: string,
    content: string,
    parentId?: string | null,
    mentionUserIds?: string[]
) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };
    if (!content.trim()) return { success: false, error: "Comment content is required" };

    const comment = await prisma.teamComment.create({
        data: {
            application_id: applicationId,
            author_id: user.id,
            content: content.trim(),
            parent_id: parentId || null,
            mentions: mentionUserIds?.length
                ? {
                    create: mentionUserIds.map((uid) => ({
                        user_id: uid,
                    })),
                }
                : undefined,
        },
        include: {
            author: { select: { id: true, name: true, avatar_url: true } },
            mentions: { include: { user: { select: { id: true, name: true } } } },
        },
    });

    // Notify mentioned users
    if (mentionUserIds?.length) {
        await Promise.allSettled(
            mentionUserIds.map((uid) =>
                prisma.notification.create({
                    data: {
                        user_id: uid,
                        type: "mention",
                        title: `${user.name} mentioned you`,
                        message: content.length > 100 ? content.substring(0, 100) + "..." : content,
                        link: `/dashboard/applications/${applicationId}`,
                    },
                })
            )
        );
    }

    // Log activity
    await prisma.applicationActivity.create({
        data: {
            application_id: applicationId,
            actor_id: user.id,
            action: "team_comment",
            details: { commentId: comment.id, hasRepliedTo: !!parentId } as any,
        },
    });

    revalidatePath(`/dashboard/applications/${applicationId}`);
    return { success: true, comment };
}

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

    const comments = await prisma.teamComment.findMany({
        where: { application_id: applicationId, parent_id: null },
        include: {
            author: { select: { id: true, name: true, avatar_url: true } },
            mentions: { include: { user: { select: { id: true, name: true } } } },
            replies: {
                include: {
                    author: { select: { id: true, name: true, avatar_url: true } },
                    mentions: { include: { user: { select: { id: true, name: true } } } },
                },
                orderBy: { created_at: "asc" },
            },
        },
        orderBy: { created_at: "desc" },
    });

    return { success: true, comments };
}

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

    const comment = await prisma.teamComment.findUnique({ where: { id: commentId } });
    if (!comment) return { success: false, error: "Comment not found" };
    if (comment.author_id !== user.id) return { success: false, error: "Not your comment" };

    await prisma.teamComment.delete({ where: { id: commentId } });

    revalidatePath(`/dashboard/applications/${comment.application_id}`);
    return { success: true };
}
