import path from "node:path";
import fs from "node:fs/promises";
import { auth } from "@/lib/auth";
import { PDF_STORAGE_DIR } from "@/lib/tools/generate-pdf";

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ name: string }> },
) {
  const session = await auth();
  if (!session?.user?.id) return new Response("Unauthorized", { status: 401 });

  const { name } = await params;
  const decoded = decodeURIComponent(name);
  if (decoded.includes("/") || decoded.includes("\\") || decoded.includes("..")) {
    return new Response("Bad request", { status: 400 });
  }
  if (!decoded.toLowerCase().endsWith(".pdf")) {
    return new Response("Bad request", { status: 400 });
  }

  const filepath = path.join(PDF_STORAGE_DIR, decoded);
  try {
    const data = await fs.readFile(filepath);
    return new Response(new Uint8Array(data), {
      headers: {
        "content-type": "application/pdf",
        "content-disposition": `inline; filename="${decoded}"`,
        "cache-control": "private, max-age=3600",
      },
    });
  } catch {
    return new Response("Not found", { status: 404 });
  }
}
