import { NextRequest } from "next/server";

// Configure with env in production. Defaults to local python server.
const PY_BACKEND_URL = process.env.PY_BACKEND_URL ?? "http://localhost:8080";

function passthroughHeaders(upstreamHeaders: Headers) {
  // Avoid hop-by-hop headers and let Next set encoding/length.
  const headers = new Headers(upstreamHeaders);
  headers.delete("connection");
  headers.delete("transfer-encoding");
  headers.delete("keep-alive");
  headers.delete("proxy-authenticate");
  headers.delete("proxy-authorization");
  headers.delete("te");
  headers.delete("trailers");
  headers.delete("upgrade");
  headers.delete("content-encoding");
  return headers;
}

export async function GET(req: NextRequest) {
  const incoming = new URL(req.url);
  const file = incoming.searchParams.get("file");
  if (!file) {
    return new Response("file is required", { status: 400 });
  }

  const upstream = new URL("/serve_pdf", PY_BACKEND_URL);
  upstream.searchParams.set("file", file);

  // Important for react-pdf/pdf.js: forward Range header when present.
  const headers: Record<string, string> = {};
  const range = req.headers.get("range");
  if (range) headers["range"] = range;

  const upstreamRes = await fetch(upstream, { headers });

  return new Response(upstreamRes.body, {
    status: upstreamRes.status,
    headers: passthroughHeaders(upstreamRes.headers),
  });
}

