/**
 * POST /api/report-studio/export/pptx
 * Body: { report: BrandReport, brand: { name, domain, logoUrl? } }
 *
 * Serialises a pre-built BrandReport into a 7-slide PowerPoint deck
 * and streams it back as a downloadable file.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { exportReportToPptx } from "@/lib/services/pptx-exporter";
import type { BrandReport } from "@/lib/services/report-generator";

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

interface Body {
  report?: BrandReport;
  brand?: { name?: string; domain?: string; logoUrl?: string };
}

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 Body | null;
  if (!body?.report || !body?.brand?.name || !body?.brand?.domain) {
    return NextResponse.json(
      { error: "report and brand { name, domain } are required" },
      { status: 400 },
    );
  }

  const buffer = await exportReportToPptx(body.report, {
    name: body.brand.name,
    domain: body.brand.domain,
    logoUrl: body.brand.logoUrl,
  });

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

  return new NextResponse(new Uint8Array(buffer), {
    headers: {
      "Content-Type": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
      "Content-Disposition": `attachment; filename="${fileBase}.pptx"`,
    },
  });
}
