"use server";

import { prisma } from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";
import { revalidatePath } from "next/cache";
import { PIPELINE_TEMPLATES, PipelineTemplate, StageInput } from "@/lib/pipelineConstants";

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

    const pipelines = await prisma.hiringPipeline.findMany({
        where: { employer_id: user.id, job_id: null }, // template pipelines (not job-specific)
        include: {
            stages: { orderBy: { order: "asc" } },
            _count: { select: { stages: true } }
        },
        orderBy: { created_at: "desc" }
    });

    return { success: true, pipelines };
}

export async function createPipeline(name: string, stages: StageInput[], templateKey?: string) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    if (!name.trim()) return { success: false, error: "Pipeline name is required" };
    if (stages.length < 2) return { success: false, error: "Pipeline must have at least 2 stages" };
    if (stages.length > 12) return { success: false, error: "Pipeline cannot have more than 12 stages" };

    const pipeline = await prisma.hiringPipeline.create({
        data: {
            employer_id: user.id,
            name: name.trim(),
            is_default: false,
            stages: {
                create: stages.map((s, i) => ({
                    name: s.name,
                    color: s.color,
                    description: s.description || null,
                    stage_type: s.stage_type || "interview",
                    order: s.order ?? i,
                    expected_duration_days: s.expected_duration_days ?? null
                }))
            }
        },
        include: { stages: { orderBy: { order: "asc" } } }
    });

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

export async function updatePipeline(pipelineId: string, name: string, stages: StageInput[]) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    const existing = await prisma.hiringPipeline.findUnique({
        where: { id: pipelineId },
        include: { stages: true }
    });
    if (!existing || existing.employer_id !== user.id) return { success: false, error: "Pipeline not found" };

    // Delete old stages and recreate — simplest approach for template pipelines
    await prisma.hiringStage.deleteMany({ where: { pipeline_id: pipelineId } });

    const updated = await prisma.hiringPipeline.update({
        where: { id: pipelineId },
        data: {
            name: name.trim(),
            stages: {
                create: stages.map((s, i) => ({
                    name: s.name,
                    color: s.color,
                    description: s.description || null,
                    stage_type: s.stage_type || "interview",
                    order: s.order ?? i,
                    expected_duration_days: s.expected_duration_days ?? null
                }))
            }
        },
        include: { stages: { orderBy: { order: "asc" } } }
    });

    revalidatePath("/dashboard/ats/pipelines");
    return { success: true, pipeline: updated };
}

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

    const pipeline = await prisma.hiringPipeline.findUnique({
        where: { id: pipelineId },
        include: { stages: { include: { _count: { select: { applications: true } } } } }
    });
    if (!pipeline || pipeline.employer_id !== user.id) return { success: false, error: "Not found" };

    const hasActiveCandidates = pipeline.stages.some(s => s._count.applications > 0);
    if (hasActiveCandidates) return { success: false, error: "Pipeline has active candidates. Move them before deleting." };

    await prisma.hiringPipeline.delete({ where: { id: pipelineId } });
    revalidatePath("/dashboard/ats/pipelines");
    return { success: true };
}

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

    const original = await prisma.hiringPipeline.findUnique({
        where: { id: pipelineId },
        include: { stages: { orderBy: { order: "asc" } } }
    });
    if (!original || original.employer_id !== user.id) return { success: false, error: "Not found" };

    const copy = await prisma.hiringPipeline.create({
        data: {
            employer_id: user.id,
            name: `${original.name} (Copy)`,
            is_default: false,
            stages: {
                create: original.stages.map(s => ({
                    name: s.name,
                    color: s.color,
                    description: (s as any).description || null,
                    stage_type: (s as any).stage_type || "interview",
                    order: s.order,
                    expected_duration_days: (s as any).expected_duration_days ?? null
                }))
            }
        },
        include: { stages: { orderBy: { order: "asc" } } }
    });

    revalidatePath("/dashboard/ats/pipelines");
    return { success: true, pipeline: copy };
}

export async function createPipelineFromTemplate(templateKey: PipelineTemplate) {
    const template = PIPELINE_TEMPLATES[templateKey];
    if (!template) return { success: false, error: "Invalid template" };
    return createPipeline(template.name, [...template.stages] as StageInput[]);
}
