"use server";

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

export interface StageConfig {
    entry: {
        sendCandidateEmail: boolean;
        emailTemplate?: string;
        createTask: boolean;
        taskTitle?: string;
        taskDueDays?: number;
    };
    exit: {
        requireScore: boolean;
        requireNote: boolean;
        requireInterview: boolean;
        requireDocument: boolean;
        requireApproval: boolean;
    };
    timeLimit: {
        warningAfterDays?: number;
        maxDays?: number;
        autoActionAfterDays?: number;
        autoAction?: "send_email" | "flag" | "archive" | null;
    };
}

export async function getStageConfig(stageId: string) {
    const stage = await prisma.hiringStage.findUnique({ where: { id: stageId } });
    if (!stage) return { success: false, error: "Stage not found" };
    const config = (stage.actions as StageConfig | null) ?? {
        entry: { sendCandidateEmail: false, createTask: false },
        exit: { requireScore: false, requireNote: false, requireInterview: false, requireDocument: false, requireApproval: false },
        timeLimit: {}
    };
    return { success: true, config, stage };
}

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

    // Verify stage belongs to employer
    const stage = await prisma.hiringStage.findUnique({
        where: { id: stageId },
        include: { pipeline: true }
    });
    if (!stage || stage.pipeline.employer_id !== user.id) return { success: false, error: "Forbidden" };

    await prisma.hiringStage.update({
        where: { id: stageId },
        data: { actions: config as any }
    });

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

export async function validateStageTransition(applicationId: string, toStageId: string): Promise<{ valid: boolean; blockers: string[] }> {
    const application = await prisma.application.findUnique({
        where: { id: applicationId },
        include: {
            current_stage: true,
            interviews: { orderBy: { scheduled_start_datetime: "desc" }, take: 1 },
            score: true,
            candidate_notes: { take: 1 }
        }
    });

    if (!application) return { valid: false, blockers: ["Application not found"] };

    const toStage = await prisma.hiringStage.findUnique({ where: { id: toStageId } });
    if (!toStage) return { valid: false, blockers: ["Target stage not found"] };

    const currentStage = application.current_stage;
    const config = currentStage?.actions as StageConfig | null;
    const blockers: string[] = [];

    if (config?.exit?.requireScore && !application.score) {
        blockers.push("A score must be added before advancing from this stage.");
    }
    if (config?.exit?.requireNote && application.candidate_notes.length === 0) {
        blockers.push("Add at least one note before advancing.");
    }
    if (config?.exit?.requireInterview && application.interviews.length === 0) {
        blockers.push("An interview must be scheduled or completed first.");
    }

    return { valid: blockers.length === 0, blockers };
}

export async function bulkMoveApplications(applicationIds: string[], toStageId: string, note?: string) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    const toStage = await prisma.hiringStage.findUnique({
        where: { id: toStageId },
        include: { pipeline: true }
    });
    if (!toStage || toStage.pipeline.employer_id !== user.id) return { success: false, error: "Forbidden" };

    const results = await Promise.all(applicationIds.map(async (appId) => {
        try {
            const existing = await prisma.application.findUnique({
                where: { id: appId },
                select: { current_stage_id: true }
            });
            if (!existing) return { id: appId, success: false };

            // Close old stage history
            if (existing.current_stage_id) {
                await prisma.candidateStageHistory.updateMany({
                    where: { application_id: appId, stage_id: existing.current_stage_id, left_at: null },
                    data: {
                        left_at: new Date(),
                        duration_days: Math.floor((Date.now() - Date.now()) / (1000 * 60 * 60 * 24))
                    }
                });
            }
            // Create new stage history
            await prisma.candidateStageHistory.create({
                data: { application_id: appId, stage_id: toStageId, actor_id: user.id, notes: note || null }
            });
            // Update application
            await prisma.application.update({
                where: { id: appId },
                data: { current_stage_id: toStageId, updated_at: new Date() }
            });

            return { id: appId, success: true };
        } catch (error) {
            console.error("Bulk move stage error:", error);
            return { id: appId, success: false };
        }
    }));

    const moved = results.filter(r => r.success).length;
    return { success: true, moved, failed: results.length - moved };
}
