import { NextResponse } from "next/server";
import { promises as fs } from "fs";
import path from "path";

export const dynamic = "force-dynamic";

const TEST_PDF_DIR = path.join(process.cwd(), "test");

const safeResolveTestPdf = (name: string) => {
  const trimmed = (name ?? "").trim();
  if (!trimmed) return null;
  // 防止目录穿越：只允许同目录文件名
  if (trimmed.includes("/") || trimmed.includes("\\") || trimmed.includes("..")) {
    return null;
  }
  if (!trimmed.toLowerCase().endsWith(".pdf")) {
    return null;
  }
  return path.join(TEST_PDF_DIR, trimmed);
};

export async function GET(request: Request) {
  // 仅用于本地测试文件的“真跳页链接”
  // 生产环境不应该暴露本地磁盘文件，因此默认只允许非生产环境访问
  if (process.env.NODE_ENV === "production") {
    return NextResponse.json({ error: "生产环境不支持 test-pdf" }, { status: 404 });
  }

  const url = new URL(request.url);
  const name = url.searchParams.get("name") ?? "";
  const file = safeResolveTestPdf(name);
  if (!file) {
    return NextResponse.json({ error: "文件名非法" }, { status: 400 });
  }

  try {
    const buffer = await fs.readFile(file);
    return new NextResponse(buffer, {
      headers: {
        "Content-Type": "application/pdf",
        // 内嵌预览，浏览器 PDF 查看器可识别 #page=
        "Content-Disposition": `inline; filename*=UTF-8''${encodeURIComponent(name)}`,
        "Cache-Control": "no-store",
      },
    });
  } catch (error) {
    return NextResponse.json({ error: `读取 PDF 失败：${String(error)}` }, { status: 404 });
  }
}

