// GET /api/cf/[id]/pdf — Plan 003, Faza F.
//
// Streams the CF extract PDF from gis-api back to the browser. The thin
// client's getPdf() returns the raw Response so we can pipe the body
// without buffering it in Node memory.
//
// Filename: tries to read documentName from gis-api.cf.get(id) first; falls
// back to "cf-<id>.pdf". A failure on the metadata lookup is non-fatal —
// the PDF stream is what matters.
import { NextResponse } from "next/server";
import { getAuthSession } from "@/core/auth/require-auth";
import { gisApi, GisApiError } from "@/lib/gis-api-client";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

function sanitizeFilename(name: string): string {
  // ASCII-safe, no path separators or quotes.
  return name.replace(/[\\/"\r\n\t]/g, "_").slice(0, 200);
}

export async function GET(
  _request: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const session = await getAuthSession();
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  if (!id) {
    return NextResponse.json({ error: "missing_id" }, { status: 400 });
  }

  // Best-effort filename resolution. Non-fatal on failure.
  let filename = `cf-${id}.pdf`;
  try {
    const meta = await gisApi.enrichment.cf.get(id);
    const fromDoc = meta.documentName?.trim();
    const fromCadastral = meta.nrCadastral?.trim();
    if (fromDoc) {
      filename = fromDoc.toLowerCase().endsWith(".pdf")
        ? fromDoc
        : `${fromDoc}.pdf`;
    } else if (fromCadastral) {
      filename = `extras-cf-${fromCadastral}.pdf`;
    }
  } catch {
    /* keep default filename */
  }

  try {
    const upstream = await gisApi.enrichment.cf.getPdf(id);
    const headers = new Headers();
    headers.set(
      "Content-Type",
      upstream.headers.get("Content-Type") || "application/pdf",
    );
    const len = upstream.headers.get("Content-Length");
    if (len) headers.set("Content-Length", len);
    headers.set(
      "Content-Disposition",
      `attachment; filename="${sanitizeFilename(filename)}"`,
    );
    headers.set("Cache-Control", "private, no-store");
    return new Response(upstream.body, { status: 200, headers });
  } catch (err) {
    if (err instanceof GisApiError) {
      return NextResponse.json(
        { error: err.code, status: err.status, body: err.body },
        { status: err.status },
      );
    }
    const msg = err instanceof Error ? err.message : String(err);
    console.error("[cf-pdf] internal error:", msg);
    return NextResponse.json(
      { error: "internal_error", hint: msg.slice(0, 200) },
      { status: 500 },
    );
  }
}
