import { NextRequest, NextResponse } from "next/server";
import { readFile } from "node:fs/promises";
import path from "node:path";

const SPECS_ROOT = path.join(process.cwd(), "specs", "openapi");

const CONTENT_TYPES: Record<string, string> = {
  ".yaml": "application/yaml; charset=utf-8",
  ".yml": "application/yaml; charset=utf-8",
  ".json": "application/json; charset=utf-8",
};

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ path: string[] }> },
) {
  const { path: segments } = await params;
  const relativePath = segments.join("/");
  const filePath = path.normalize(path.join(SPECS_ROOT, relativePath));

  if (!filePath.startsWith(SPECS_ROOT)) {
    return NextResponse.json({ message: "Not found" }, { status: 404 });
  }

  try {
    const content = await readFile(filePath, "utf8");
    const ext = path.extname(filePath);
    return new NextResponse(content, {
      status: 200,
      headers: {
        "Content-Type": CONTENT_TYPES[ext] ?? "text/plain; charset=utf-8",
        "Cache-Control": "public, max-age=60",
      },
    });
  } catch {
    return NextResponse.json({ message: "Not found" }, { status: 404 });
  }
}
