import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { evaluationToCsvRows } from "@/lib/export-utils";

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 rows = evaluationToCsvRows(evaluation as Parameters<typeof evaluationToCsvRows>[0]);
    const csv = rows.map((r) => r.map((c) => `"${String(c).replace(/"/g, '""')}"`).join(",")).join("\n");

    return new NextResponse(csv, {
      headers: {
        "Content-Type": "text/csv",
        "Content-Disposition": `attachment; filename="evaluation-${id}.csv"`,
      },
    });
  } catch (e) {
    console.error(e);
    return NextResponse.json({ error: "Export failed" }, { status: 500 });
  }
}
