import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { jsPDF } from "jspdf";
import autoTable from "jspdf-autotable";
import { format } from "date-fns";

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const id = searchParams.get("id");
    if (!id) {
      return NextResponse.json({ error: "Evaluation id required" }, { status: 400 });
    }

    const evaluation = await prisma.evaluation.findUnique({
      where: { id },
      include: {
        template: true,
        dimensionScores: { include: { dimension: true } },
      },
    });

    if (!evaluation) {
      return NextResponse.json({ error: "Evaluation not found" }, { status: 404 });
    }

    const doc = new jsPDF();
    doc.setFontSize(18);
    doc.text("Évaluation Maturité IA Gen", 14, 20);
    doc.setFontSize(10);
    const teamStr = evaluation.candidateTeam ? ` | Équipe : ${evaluation.candidateTeam}` : "";
    doc.text(`Candidat : ${evaluation.candidateName} | Rôle : ${evaluation.candidateRole}${teamStr}`, 14, 28);
    doc.text(`Évaluateur : ${evaluation.evaluatorName} | Date : ${format(evaluation.evaluationDate, "yyyy-MM-dd")}`, 14, 34);
    doc.text(`Modèle : ${evaluation.template?.name ?? ""} | Statut : ${evaluation.status === "submitted" ? "Soumise" : "Brouillon"}`, 14, 40);

    const tableData = evaluation.dimensionScores.map((ds) => [
      ds.dimension.title,
      String(ds.score ?? "-"),
      ds.justification ?? "",
      ds.confidence ?? "",
    ]);

    autoTable(doc, {
      startY: 48,
      head: [["Dimension", "Score", "Justification", "Confiance"]],
      body: tableData,
      theme: "striped",
    });

    const finalY =
      (doc as unknown as { lastAutoTable?: { finalY: number } }).lastAutoTable?.finalY ?? 48;
    doc.setFontSize(10);
    doc.text("Synthèse :", 14, finalY + 12);
    doc.text(evaluation.findings ?? "N/A", 14, finalY + 18, { maxWidth: 180 });
    doc.text("Recommandations :", 14, finalY + 28);
    doc.text(evaluation.recommendations ?? "N/A", 14, finalY + 34, { maxWidth: 180 });

    const buf = Buffer.from(doc.output("arraybuffer"));
    return new NextResponse(buf, {
      headers: {
        "Content-Type": "application/pdf",
        "Content-Disposition": `attachment; filename="evaluation-${id}.pdf"`,
      },
    });
  } catch (e) {
    console.error(e);
    return NextResponse.json({ error: "Export failed" }, { status: 500 });
  }
}
