import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { evaluationToConfluenceMarkup } 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 markup = evaluationToConfluenceMarkup(
      evaluation as Parameters<typeof evaluationToConfluenceMarkup>[0]
    );

    return new NextResponse(markup, {
      headers: {
        "Content-Type": "text/plain; charset=utf-8",
        "Content-Disposition": `attachment; filename="guide-entretien-${id}.md"`,
      },
    });
  } catch (e) {
    console.error(e);
    return NextResponse.json({ error: "Export failed" }, { status: 500 });
  }
}
