import { NextRequest, NextResponse } from "next/server";
import { getBackendUrl } from "@/lib/backend";

export async function GET(
  req: NextRequest,
  { params }: { params: { token: string } }
) {
  const targetUrl = getBackendUrl(`exports/download/${params.token}`);
  const forwardedFor = req.headers.get("x-forwarded-for") ?? "";
  const userAgent = req.headers.get("user-agent") ?? "";
  const headers: Record<string, string> = {};
  if (forwardedFor) headers["X-Forwarded-For"] = forwardedFor;
  if (userAgent) headers["User-Agent"] = userAgent;

  try {
    const res = await fetch(targetUrl, { method: "GET", headers });
    const body = await res.arrayBuffer();
    return new NextResponse(body, {
      status: res.status,
      headers: {
        "Content-Type": res.headers.get("content-type") ?? "application/octet-stream",
        "Content-Disposition": res.headers.get("content-disposition") ?? "attachment",
        "Cache-Control": "no-store",
      },
    });
  } catch {
    return NextResponse.json(
      {
        data: null,
        meta: { timestamp: new Date().toISOString(), version: "v1" },
        error: { message: "Backend unavailable." },
      },
      { status: 503 }
    );
  }
}
