"use server";

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

// ─── Bulk Move ──────────────────────────────────────────
export async function bulkMoveToStage(applicationIds: string[], targetStageId: string, note?: string) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };
    if (applicationIds.length === 0) return { success: false, error: "No candidates selected" };
    if (applicationIds.length > 100) return { success: false, error: "Maximum 100 candidates per bulk action" };

    // Verify target stage belongs to employer
    const targetStage = await prisma.hiringStage.findUnique({
        where: { id: targetStageId },
        include: { pipeline: { select: { employer_id: true } } },
    });
    if (!targetStage || targetStage.pipeline.employer_id !== user.id) {
        return { success: false, error: "Target stage not found" };
    }

    const now = new Date();
    const results = await Promise.allSettled(
        applicationIds.map(async (appId) => {
            // Close existing stage history entry
            await prisma.candidateStageHistory.updateMany({
                where: { application_id: appId, left_at: null },
                data: {
                    left_at: now,
                    duration_days: Math.round((now.getTime() - now.getTime()) / (1000 * 60 * 60 * 24)),
                },
            });

            // Update application
            await prisma.application.update({
                where: { id: appId },
                data: { current_stage_id: targetStageId },
            });

            // Create new history entry
            await prisma.candidateStageHistory.create({
                data: {
                    application_id: appId,
                    stage_id: targetStageId,
                    actor_id: user.id,
                    notes: note || `Bulk moved to ${targetStage.name}`,
                    entered_at: now,
                },
            });

            return appId;
        })
    );

    const succeeded = results.filter(r => r.status === "fulfilled").length;
    const failed = results.filter(r => r.status === "rejected").length;

    revalidatePath("/dashboard/applications");
    revalidatePath("/dashboard/ats");

    return {
        success: true,
        moved: succeeded,
        failed,
        message: `${succeeded} candidates moved to ${targetStage.name}${failed > 0 ? `, ${failed} failed` : ""}`,
    };
}

// ─── Bulk Reject ────────────────────────────────────────
export async function bulkReject(applicationIds: string[], reason: string, sendEmail: boolean = false) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };
    if (applicationIds.length === 0) return { success: false, error: "No candidates selected" };
    if (!reason.trim()) return { success: false, error: "Rejection reason is required" };

    const now = new Date();
    const results = await Promise.allSettled(
        applicationIds.map(async (appId) => {
            // Close existing stage history
            await prisma.candidateStageHistory.updateMany({
                where: { application_id: appId, left_at: null },
                data: { left_at: now },
            });

            // Update application status
            await prisma.application.update({
                where: { id: appId },
                data: {
                    status: "rejected",
                    current_stage_id: null,
                    notes: reason,
                },
            });

            // Log activity
            await prisma.applicationActivity.create({
                data: {
                    application_id: appId,
                    actor_id: user.id,
                    action: "bulk_rejected",
                    details: { reason, sendEmail } as any,
                },
            });

            return appId;
        })
    );

    const succeeded = results.filter(r => r.status === "fulfilled").length;
    const failed = results.filter(r => r.status === "rejected").length;

    revalidatePath("/dashboard/applications");
    revalidatePath("/dashboard/ats");

    return {
        success: true,
        rejected: succeeded,
        failed,
        message: `${succeeded} candidates rejected${failed > 0 ? `, ${failed} failed` : ""}`,
    };
}

// ─── Bulk Tag ───────────────────────────────────────────
export async function bulkAddTag(applicationIds: string[], tagId: string) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };
    if (applicationIds.length === 0) return { success: false, error: "No candidates selected" };

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

    const results = await Promise.allSettled(
        applicationIds.map(async (appId) => {
            // Upsert to avoid duplicates
            await prisma.applicationTag.upsert({
                where: { application_id_tag_id: { application_id: appId, tag_id: tagId } },
                create: { application_id: appId, tag_id: tagId },
                update: {},
            });
            return appId;
        })
    );

    const succeeded = results.filter(r => r.status === "fulfilled").length;
    revalidatePath("/dashboard/applications");

    return {
        success: true,
        tagged: succeeded,
        message: `Tag "${tag.name}" applied to ${succeeded} candidates`,
    };
}

// ─── Bulk Remove Tag ────────────────────────────────────
export async function bulkRemoveTag(applicationIds: string[], tagId: string) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    await prisma.applicationTag.deleteMany({
        where: {
            application_id: { in: applicationIds },
            tag_id: tagId,
        },
    });

    revalidatePath("/dashboard/applications");

    return {
        success: true,
        message: `Tag removed from ${applicationIds.length} candidates`,
    };
}

// ─── Bulk Add Note ──────────────────────────────────────
export async function bulkAddNote(applicationIds: string[], content: string, isPrivate: boolean = false) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };
    if (!content.trim()) return { success: false, error: "Note content is required" };

    const results = await Promise.allSettled(
        applicationIds.map(async (appId) => {
            await prisma.candidateNote.create({
                data: {
                    application_id: appId,
                    author_id: user.id,
                    content: content.trim(),
                    is_private: isPrivate,
                },
            });
            return appId;
        })
    );

    const succeeded = results.filter(r => r.status === "fulfilled").length;
    revalidatePath("/dashboard/applications");

    return {
        success: true,
        noted: succeeded,
        message: `Note added to ${succeeded} candidates`,
    };
}

// ─── Bulk Email ─────────────────────────────────────────
export async function bulkSendMessage(applicationIds: string[], subject: string, content: string) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };
    if (!content.trim()) return { success: false, error: "Message content is required" };

    const results = await Promise.allSettled(
        applicationIds.map(async (appId) => {
            // Ensure conversation exists
            let conversation = await prisma.conversation.findUnique({
                where: { application_id: appId }
            });

            if (!conversation) {
                const app = await prisma.application.findUnique({
                    where: { id: appId },
                    select: { candidate_id: true, job: { select: { title: true } } },
                });
                if (app) {
                    conversation = await prisma.conversation.create({
                        data: {
                            type: "application",
                            application_id: appId,
                            created_by: user.id,
                            title: `${app.job.title} — Direct Message`,
                            participants: {
                                create: [
                                    { user_id: user.id, role: "creator" },
                                    { user_id: app.candidate_id, role: "member" },
                                ],
                            },
                        },
                    });
                }
            }

            if (conversation) {
                const contentText = `**${subject}**\n\n${content}`;

                await prisma.$transaction([
                    prisma.message.create({
                        data: {
                            conversation_id: conversation.id,
                            sender_id: user.id,
                            content: contentText,
                            message_type: "text",
                        },
                    }),
                    prisma.conversation.update({
                        where: { id: conversation.id },
                        data: {
                            last_message_at: new Date(),
                            last_message_preview: contentText.substring(0, 200),
                        },
                    }),
                    prisma.conversationParticipant.updateMany({
                        where: { conversation_id: conversation.id, user_id: { not: user.id } },
                        data: { unread_count: { increment: 1 } },
                    }),
                ]);

                // Notify other participants
                const otherParticipants = await prisma.conversationParticipant.findMany({
                    where: {
                        conversation_id: conversation.id,
                        user_id: { not: user.id },
                        left_at: null,
                    },
                    select: { user_id: true }
                });

                if (otherParticipants.length > 0) {
                    await prisma.notification.createMany({
                        data: otherParticipants.map(p => ({
                            user_id: p.user_id,
                            type: "new_message",
                            title: `New message from ${user.name || "someone"}`,
                            message: contentText.substring(0, 80) + (contentText.length > 80 ? "..." : ""),
                            link: `/dashboard/messages/${appId}`,
                        }))
                    });
                }
            }
            return appId;
        })
    );

    const succeeded = results.filter(r => r.status === "fulfilled").length;
    revalidatePath("/dashboard/messages");

    return {
        success: true,
        sent: succeeded,
        message: `Message sent to ${succeeded} candidates`,
    };
}

// ─── Bulk Archive ───────────────────────────────────────
export async function bulkArchive(applicationIds: string[]) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    await prisma.application.updateMany({
        where: {
            id: { in: applicationIds },
            job: { employer_id: user.id },
        },
        data: { is_withdrawn: true },
    });

    revalidatePath("/dashboard/applications");
    revalidatePath("/dashboard/ats");

    return {
        success: true,
        message: `${applicationIds.length} candidates archived`,
    };
}

// ─── Get Employer Tags (for bulk tag modal) ─────────────
export async function getEmployerTags() {
    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" },
        include: { _count: { select: { applications: true } } },
    });

    return { success: true, tags };
}

// ─── Get Employer Stages (for bulk move modal) ──────────
export async function getEmployerStages() {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    const stages = await prisma.hiringStage.findMany({
        where: { pipeline: { employer_id: user.id } },
        include: {
            pipeline: { select: { name: true } },
            _count: { select: { applications: true } },
        },
        orderBy: { order: "asc" },
    });

    return { success: true, stages };
}
