"use server";

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

// ─── KPI Cards ──────────────────────────────────────────
export async function getPipelineKPIs() {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    const now = new Date();
    const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);

    // Total applications for this employer's jobs
    const totalApplicants = await prisma.application.count({
        where: { job: { employer_id: user.id } },
    });

    // Active in pipeline (not rejected/hired, not withdrawn)
    const activeCandidates = await prisma.application.count({
        where: {
            job: { employer_id: user.id },
            status: { notIn: ["rejected", "hired"] },
            is_withdrawn: false,
        },
    });

    // Hired this month
    const hiredThisMonth = await prisma.application.count({
        where: {
            job: { employer_id: user.id },
            status: "hired",
            updated_at: { gte: thirtyDaysAgo },
        },
    });

    // Average time-to-hire (for hired apps with stage history)
    const hiredApps = await prisma.application.findMany({
        where: {
            job: { employer_id: user.id },
            status: "hired",
        },
        select: { applied_at: true, updated_at: true },
        take: 100,
        orderBy: { updated_at: "desc" },
    });

    let avgTimeToHire = 0;
    if (hiredApps.length > 0) {
        const totalDays = hiredApps.reduce((sum, app) => {
            const diffMs = app.updated_at.getTime() - app.applied_at.getTime();
            return sum + diffMs / (1000 * 60 * 60 * 24);
        }, 0);
        avgTimeToHire = Math.round(totalDays / hiredApps.length);
    }

    // Conversion rate (hired / total)
    const conversionRate = totalApplicants > 0
        ? Math.round((hiredThisMonth / Math.max(1, totalApplicants)) * 10000) / 100
        : 0;

    // In interview stage
    const inInterview = await prisma.application.count({
        where: {
            job: { employer_id: user.id },
            status: "interview",
            is_withdrawn: false,
        },
    });

    return {
        success: true,
        kpis: {
            totalApplicants,
            activeCandidates,
            hiredThisMonth,
            avgTimeToHire,
            conversionRate,
            inInterview,
        },
    };
}

// ─── Conversion Funnel ──────────────────────────────────
export async function getConversionFunnel() {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    // Get all pipelines for employer
    const pipelines = await prisma.hiringPipeline.findMany({
        where: { employer_id: user.id },
        include: {
            stages: {
                orderBy: { order: "asc" },
                include: {
                    _count: { select: { applications: true, history: true } },
                },
            },
        },
    });

    // Aggregate all stages across all pipelines
    const stageData: Array<{
        name: string;
        color: string;
        currentCount: number;
        totalPassed: number;
        order: number;
    }> = [];

    for (const pipeline of pipelines) {
        for (const stage of pipeline.stages) {
            stageData.push({
                name: stage.name,
                color: stage.color,
                currentCount: stage._count.applications,
                totalPassed: stage._count.history,
                order: stage.order,
            });
        }
    }

    // Merge duplicates by stage name (e.g., multiple pipelines have "Applied")
    const merged = new Map<string, { name: string; color: string; currentCount: number; totalPassed: number; order: number }>();
    for (const s of stageData) {
        const existing = merged.get(s.name);
        if (existing) {
            existing.currentCount += s.currentCount;
            existing.totalPassed += s.totalPassed;
        } else {
            merged.set(s.name, { ...s });
        }
    }

    const funnel = Array.from(merged.values()).sort((a, b) => a.order - b.order);

    return { success: true, funnel };
}

// ─── Time-in-Stage Metrics ──────────────────────────────
export async function getTimeMetrics() {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    // Get completed stage histories (have both entered_at and left_at)
    const histories = await prisma.candidateStageHistory.findMany({
        where: {
            application: { job: { employer_id: user.id } },
            left_at: { not: null },
        },
        include: {
            stage: { select: { name: true, color: true, order: true } },
        },
        orderBy: { entered_at: "desc" },
        take: 500,
    });

    // Group by stage name
    const stageMap = new Map<string, { name: string; color: string; order: number; durations: number[] }>();

    for (const h of histories) {
        if (!h.left_at) continue;
        const days = h.duration_days ?? Math.round((h.left_at.getTime() - h.entered_at.getTime()) / (1000 * 60 * 60 * 24));
        const key = h.stage.name;
        const existing = stageMap.get(key);
        if (existing) {
            existing.durations.push(days);
        } else {
            stageMap.set(key, { name: h.stage.name, color: h.stage.color, order: h.stage.order, durations: [days] });
        }
    }

    const timeMetrics = Array.from(stageMap.values())
        .map(s => ({
            stage: s.name,
            color: s.color,
            order: s.order,
            avgDays: Math.round((s.durations.reduce((a, b) => a + b, 0) / s.durations.length) * 10) / 10,
            minDays: Math.min(...s.durations),
            maxDays: Math.max(...s.durations),
            count: s.durations.length,
        }))
        .sort((a, b) => a.order - b.order);

    return { success: true, timeMetrics };
}

// ─── Bottleneck Detection ───────────────────────────────
export async function getBottlenecks() {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    const now = new Date();

    // Get stages with candidates currently in them AND their expected duration
    const stages = await prisma.hiringStage.findMany({
        where: { pipeline: { employer_id: user.id } },
        include: {
            applications: {
                where: { is_withdrawn: false, status: { notIn: ["rejected", "hired"] } },
                select: {
                    id: true,
                    applied_at: true,
                    current_stage_id: true,
                    stage_history: {
                        where: { left_at: null },
                        select: { entered_at: true },
                        take: 1,
                        orderBy: { entered_at: "desc" },
                    },
                },
            },
            pipeline: { select: { name: true } },
        },
    });

    const bottlenecks: Array<{
        stageName: string;
        stageColor: string;
        pipelineName: string;
        candidatesStuck: number;
        avgDaysStuck: number;
        severity: "low" | "medium" | "high" | "critical";
    }> = [];

    for (const stage of stages) {
        if (stage.applications.length === 0) continue;

        const stuckCandidates: number[] = [];
        for (const app of stage.applications) {
            const enteredAt = app.stage_history[0]?.entered_at ?? app.applied_at;
            const daysInStage = Math.round((now.getTime() - enteredAt.getTime()) / (1000 * 60 * 60 * 24));
            if (daysInStage >= 3) { // 3+ days = potentially stuck
                stuckCandidates.push(daysInStage);
            }
        }

        if (stuckCandidates.length > 0) {
            const avgDays = Math.round(stuckCandidates.reduce((a, b) => a + b, 0) / stuckCandidates.length);
            let severity: "low" | "medium" | "high" | "critical" = "low";
            if (avgDays >= 14 || stuckCandidates.length >= 10) severity = "critical";
            else if (avgDays >= 7 || stuckCandidates.length >= 5) severity = "high";
            else if (avgDays >= 5 || stuckCandidates.length >= 3) severity = "medium";

            bottlenecks.push({
                stageName: stage.name,
                stageColor: stage.color,
                pipelineName: stage.pipeline.name,
                candidatesStuck: stuckCandidates.length,
                avgDaysStuck: avgDays,
                severity,
            });
        }
    }

    bottlenecks.sort((a, b) => {
        const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
        return severityOrder[a.severity] - severityOrder[b.severity];
    });

    return { success: true, bottlenecks };
}

// ─── Source Effectiveness ───────────────────────────────
export async function getSourceEffectiveness() {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    const applications = await prisma.application.findMany({
        where: { job: { employer_id: user.id } },
        select: { source: true, status: true, applied_at: true, updated_at: true },
    });

    const sourceMap = new Map<string, { total: number; hired: number; rejected: number; active: number; totalDays: number }>();

    for (const app of applications) {
        const src = app.source || "Direct";
        const existing = sourceMap.get(src) ?? { total: 0, hired: 0, rejected: 0, active: 0, totalDays: 0 };
        existing.total++;
        if (app.status === "hired") {
            existing.hired++;
            existing.totalDays += Math.round((app.updated_at.getTime() - app.applied_at.getTime()) / (1000 * 60 * 60 * 24));
        }
        if (app.status === "rejected") existing.rejected++;
        if (!["hired", "rejected"].includes(app.status)) existing.active++;
        sourceMap.set(src, existing);
    }

    const sources = Array.from(sourceMap.entries()).map(([name, data]) => ({
        source: name,
        total: data.total,
        hired: data.hired,
        rejected: data.rejected,
        active: data.active,
        conversionRate: data.total > 0 ? Math.round((data.hired / data.total) * 10000) / 100 : 0,
        avgTimeToHire: data.hired > 0 ? Math.round(data.totalDays / data.hired) : null,
    }))
        .sort((a, b) => b.total - a.total);

    return { success: true, sources };
}

// ─── Drop-off Analysis ──────────────────────────────────
export async function getDropOffAnalysis() {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    // Get rejection counts by status
    const statusCounts = await prisma.application.groupBy({
        by: ["status"],
        where: { job: { employer_id: user.id } },
        _count: { id: true },
    });

    const total = statusCounts.reduce((sum, s) => sum + s._count.id, 0);
    const breakdown = statusCounts.map(s => ({
        status: s.status,
        count: s._count.id,
        percentage: total > 0 ? Math.round((s._count.id / total) * 10000) / 100 : 0,
    }));

    // Withdrawn applications
    const withdrawnCount = await prisma.application.count({
        where: { job: { employer_id: user.id }, is_withdrawn: true },
    });

    return {
        success: true,
        dropOff: {
            total,
            breakdown,
            withdrawnCount,
            withdrawnRate: total > 0 ? Math.round((withdrawnCount / total) * 10000) / 100 : 0,
        },
    };
}

// ─── Hiring Trend (Monthly) ─────────────────────────────
export async function getHiringTrend() {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    const sixMonthsAgo = new Date();
    sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);

    const applications = await prisma.application.findMany({
        where: {
            job: { employer_id: user.id },
            applied_at: { gte: sixMonthsAgo },
        },
        select: { applied_at: true, status: true },
        orderBy: { applied_at: "asc" },
    });

    // Group by month
    const monthMap = new Map<string, { month: string; applications: number; hired: number; rejected: number }>();
    for (const app of applications) {
        const monthKey = `${app.applied_at.getFullYear()}-${String(app.applied_at.getMonth() + 1).padStart(2, "0")}`;
        const label = app.applied_at.toLocaleString("default", { month: "short", year: "2-digit" });
        const existing = monthMap.get(monthKey) ?? { month: label, applications: 0, hired: 0, rejected: 0 };
        existing.applications++;
        if (app.status === "hired") existing.hired++;
        if (app.status === "rejected") existing.rejected++;
        monthMap.set(monthKey, existing);
    }

    const trend = Array.from(monthMap.values());

    return { success: true, trend };
}
