"use server";

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

// ─── Types ──────────────────────────────────────────────
export interface ExportField {
    key: string;
    label: string;
    group: string;
    defaultIncluded: boolean;
}

export interface ExportFilters {
    stageIds?: string[];
    statuses?: string[];
    dateFrom?: string;
    dateTo?: string;
    minScore?: number;
    maxScore?: number;
    tags?: string[];
    jobId?: string;
    pipelineId?: string;
}

export interface ExportTemplate {
    id: string;
    name: string;
    description: string;
    fields: string[];
}

// ─── Available Fields ───────────────────────────────────
export const EXPORT_FIELDS: ExportField[] = [
    // Candidate Info
    { key: "candidate_name", label: "Candidate Name", group: "Candidate", defaultIncluded: true },
    { key: "candidate_email", label: "Email", group: "Candidate", defaultIncluded: true },
    { key: "candidate_phone", label: "Phone", group: "Candidate", defaultIncluded: false },
    { key: "candidate_location", label: "Location", group: "Candidate", defaultIncluded: false },
    // Application
    { key: "applied_date", label: "Applied Date", group: "Application", defaultIncluded: true },
    { key: "status", label: "Status", group: "Application", defaultIncluded: true },
    { key: "source", label: "Source", group: "Application", defaultIncluded: true },
    { key: "current_stage", label: "Current Stage", group: "Application", defaultIncluded: true },
    { key: "cover_letter", label: "Cover Letter", group: "Application", defaultIncluded: false },
    { key: "resume_url", label: "Resume Link", group: "Application", defaultIncluded: false },
    // Job
    { key: "job_title", label: "Job Title", group: "Job", defaultIncluded: true },
    { key: "job_location", label: "Job Location", group: "Job", defaultIncluded: false },
    { key: "job_type", label: "Job Type", group: "Job", defaultIncluded: false },
    // Scoring
    { key: "overall_score", label: "Overall Score", group: "Scoring", defaultIncluded: true },
    { key: "technical_score", label: "Technical Score", group: "Scoring", defaultIncluded: false },
    { key: "experience_score", label: "Experience Score", group: "Scoring", defaultIncluded: false },
    { key: "rating", label: "Rating", group: "Scoring", defaultIncluded: false },
    // Pipeline
    { key: "interview_count", label: "Interviews", group: "Pipeline", defaultIncluded: false },
    { key: "feedback_count", label: "Feedback Count", group: "Pipeline", defaultIncluded: false },
    { key: "days_in_pipeline", label: "Days in Pipeline", group: "Pipeline", defaultIncluded: false },
    { key: "tags", label: "Tags", group: "Pipeline", defaultIncluded: false },
    { key: "notes_count", label: "Notes Count", group: "Pipeline", defaultIncluded: false },
];

// ─── Templates ──────────────────────────────────────────
export const EXPORT_TEMPLATES: ExportTemplate[] = [
    {
        id: "basic",
        name: "Basic Overview",
        description: "Essential candidate info for quick reviews",
        fields: ["candidate_name", "candidate_email", "job_title", "status", "current_stage", "applied_date"],
    },
    {
        id: "detailed",
        name: "Detailed Report",
        description: "Comprehensive data for team reports",
        fields: ["candidate_name", "candidate_email", "candidate_phone", "job_title", "status",
            "current_stage", "applied_date", "source", "overall_score", "rating", "interview_count", "days_in_pipeline"],
    },
    {
        id: "scoring",
        name: "Scoring Report",
        description: "Focus on candidate scores and ratings",
        fields: ["candidate_name", "candidate_email", "job_title", "overall_score",
            "technical_score", "experience_score", "rating", "feedback_count"],
    },
    {
        id: "pipeline",
        name: "Pipeline Status",
        description: "Track pipeline progress and bottlenecks",
        fields: ["candidate_name", "job_title", "status", "current_stage",
            "days_in_pipeline", "interview_count", "notes_count", "tags"],
    },
];

// ─── Export CSV ─────────────────────────────────────────
export async function exportCandidatesCSV(
    filters: ExportFilters,
    selectedFields: string[]
): Promise<{ success: boolean; csvContent?: string; count?: number; error?: string }> {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    const applications = await fetchFilteredApplications(user.id, filters);
    if (applications.length === 0) return { success: false, error: "No candidates match filters" };

    const fields = EXPORT_FIELDS.filter(f => selectedFields.includes(f.key));
    const header = fields.map(f => f.label).join(",");

    const rows = applications.map((app: any) => {
        return fields.map(f => {
            const val = extractFieldValue(app, f.key);
            // Escape CSV
            const str = String(val ?? "");
            return str.includes(",") || str.includes('"') || str.includes("\n")
                ? `"${str.replace(/"/g, '""')}"`
                : str;
        }).join(",");
    });

    const csvContent = [header, ...rows].join("\n");

    // Log export activity
    await prisma.applicationActivity.create({
        data: {
            application_id: applications[0].id,
            actor_id: user.id,
            action: "export",
            details: { format: "csv", count: applications.length, fields: selectedFields } as any,
        },
    });

    return { success: true, csvContent, count: applications.length };
}

// ─── Export Preview ─────────────────────────────────────
export async function getExportPreview(
    filters: ExportFilters,
    selectedFields: string[],
    limit: number = 5
): Promise<{ success: boolean; preview?: any[]; totalCount?: number; error?: string }> {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    const applications = await fetchFilteredApplications(user.id, filters);
    const fields = EXPORT_FIELDS.filter(f => selectedFields.includes(f.key));

    const preview = applications.slice(0, limit).map((app: any) => {
        const row: Record<string, any> = {};
        for (const f of fields) {
            row[f.key] = extractFieldValue(app, f.key);
        }
        return row;
    });

    return { success: true, preview, totalCount: applications.length };
}

// ─── Helpers ────────────────────────────────────────────

async function fetchFilteredApplications(employerId: string, filters: ExportFilters) {
    const where: any = {
        job: { employer_id: employerId },
    };

    if (filters.jobId) where.job_id = filters.jobId;
    if (filters.statuses && filters.statuses.length > 0) where.status = { in: filters.statuses };
    if (filters.dateFrom || filters.dateTo) {
        where.applied_at = {};
        if (filters.dateFrom) where.applied_at.gte = new Date(filters.dateFrom);
        if (filters.dateTo) where.applied_at.lte = new Date(filters.dateTo);
    }
    if (filters.stageIds && filters.stageIds.length > 0) where.current_stage_id = { in: filters.stageIds };

    return prisma.application.findMany({
        where,
        include: {
            candidate: true,
            job: { select: { title: true, city: true, type: true } },
            current_stage: { select: { name: true } },
            score: true,
            interviews: { select: { id: true } },
            candidate_notes: { select: { id: true } },
            application_tags: { include: { tag: true } },
        },
        orderBy: { applied_at: "desc" },
        take: 1000, // Safety limit
    });
}

function extractFieldValue(app: any, field: string): any {
    switch (field) {
        case "candidate_name": return app.candidate?.name || "—";
        case "candidate_email": return app.candidate?.email || "—";
        case "candidate_phone": return app.candidate?.phone || "—";
        case "candidate_location": return app.candidate?.location || "—";
        case "applied_date": return app.applied_at ? new Date(app.applied_at).toLocaleDateString() : "—";
        case "status": return app.status || "—";
        case "source": return app.source || "Direct";
        case "current_stage": return app.current_stage?.name || "—";
        case "cover_letter": return app.cover_letter ? "Yes" : "No";
        case "resume_url": return app.resume_url || app.cv_link || "—";
        case "job_title": return app.job?.title || "—";
        case "job_location": return app.job?.city || "—";
        case "job_type": return app.job?.type || "—";
        case "overall_score": return app.score?.overall_score != null ? Math.round(app.score.overall_score) : "—";
        case "technical_score": return app.score?.technical_fit != null ? Math.round(app.score.technical_fit) : "—";
        case "experience_score": return app.score?.experience_relevance != null ? Math.round(app.score.experience_relevance) : "—";
        case "rating": return app.rating != null ? `${app.rating}/5` : "—";
        case "interview_count": return app.interviews?.length || 0;
        case "feedback_count": return app.interviews?.filter((i: any) => i.scorecards?.length > 0).length || 0;
        case "days_in_pipeline": return app.applied_at ? Math.floor((Date.now() - new Date(app.applied_at).getTime()) / (1000 * 60 * 60 * 24)) : "—";
        case "tags": return app.application_tags?.map((t: any) => t.tag.name).join(", ") || "—";
        case "notes_count": return app.candidate_notes?.length || 0;
        default: return "—";
    }
}

export async function getExportFields() {
    return { success: true, fields: EXPORT_FIELDS };
}

export async function getExportTemplates() {
    return { success: true, templates: EXPORT_TEMPLATES };
}
