/**
 * POST /api/report-studio/export
 * Body: { brandId, dateRange?, format: "docx" | "pdf" | "markdown" | "json" }
 *
 * Generates a BrandReport on demand and serialises it to the requested
 * format. DOCX/PDF reuse the existing exporters that the AI Strategist
 * already uses — the Report Studio hand-off is a pure data mapping in
 * src/lib/services/report-studio-export.ts.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { generateBrandReport } from "@/lib/services/report-generator";
import { logMemory } from "@/lib/services/client-memory";
import { brandReportToReportDocument } from "@/lib/services/report-studio-export";
import { renderToMarkdown } from "@/lib/services/report-export";
import { generateDocx } from "@/lib/services/docx-exporter";
import { generatePdf } from "@/lib/services/pdf-exporter";

export const dynamic = "force-dynamic";
export const maxDuration = 120;

type ExportFormat = "docx" | "pdf" | "markdown" | "json";

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

  const body = await req.json().catch(() => null) as
    | { brandId?: string; dateRange?: number; format?: ExportFormat } | null;
  if (!body?.brandId || !body.format) {
    return NextResponse.json({ error: "brandId and format required" }, { status: 400 });
  }

  const brand = await prisma.brand.findUnique({
    where: { id: body.brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });
  if (!brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const report = await generateBrandReport({
    brandId: body.brandId,
    dateRange: Number(body.dateRange) || 28,
  });

  logMemory({ brandId: body.brandId!, category: "report", action: "exported", summary: `Report exported as ${body.format} (${report.dateRange.start} — ${report.dateRange.end})`, aiContext: `Exported ${body.format} report for ${report.dateRange.days}d period` });

  const fileBase = `${brand.name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}-report-${report.dateRange.end}`;

  if (body.format === "json") {
    return NextResponse.json({ report });
  }

  const doc = brandReportToReportDocument(report);

  if (body.format === "markdown") {
    const md = renderToMarkdown(doc);
    return new NextResponse(md, {
      headers: {
        "Content-Type": "text/markdown",
        "Content-Disposition": `attachment; filename="${fileBase}.md"`,
      },
    });
  }

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

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

  return NextResponse.json({ error: "Unsupported format" }, { status: 400 });
}
