/**
 * GET /api/analysis/export?brandId=xxx&format=markdown|docx|json
 * Returns the latest completed analysis in the requested format.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { buildReportDocument, renderToMarkdown } from "@/lib/services/report-export";
import { generateDocx } from "@/lib/services/docx-exporter";
import { generatePdf } from "@/lib/services/pdf-exporter";
import type { Analysis } from "@/lib/services/analysis-schema";

export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");
  const format = searchParams.get("format") ?? "json";
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const job = await prisma.analysisJob.findFirst({
    where: { brandId, status: "completed" },
    orderBy: { createdAt: "desc" },
  });

  if (!job?.result) {
    return NextResponse.json({ error: "No completed analysis found" }, { status: 404 });
  }

  const analysis = job.result as unknown as Analysis;
  const doc = buildReportDocument(analysis);

  if (format === "pdf") {
    const buffer = await generatePdf(doc);
    const filename = `${analysis.branding?.clientDomain ?? "report"}-analysis.pdf`;
    return new NextResponse(new Uint8Array(buffer), {
      headers: {
        "Content-Type": "application/pdf",
        "Content-Disposition": `attachment; filename="${filename}"`,
      },
    });
  }

  if (format === "docx") {
    const buffer = await generateDocx(doc);
    const filename = `${analysis.branding?.clientDomain ?? "report"}-analysis.docx`;
    return new NextResponse(new Uint8Array(buffer), {
      headers: {
        "Content-Type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "Content-Disposition": `attachment; filename="${filename}"`,
      },
    });
  }

  if (format === "markdown") {
    const md = renderToMarkdown(doc);
    return new NextResponse(md, {
      headers: { "Content-Type": "text/markdown; charset=utf-8", "Content-Disposition": `attachment; filename="${analysis.branding?.clientDomain ?? "report"}-analysis.md"` },
    });
  }

  return NextResponse.json(doc);
}
