import { NextRequest, NextResponse } from "next/server";
import { readFile } from "node:fs/promises";
import { extname, join } from "node:path";

export async function GET(req: NextRequest) {
  const url = new URL(req.url);
  const p = url.searchParams.get("path");
  if (!p) return NextResponse.json({ error: "Missing path" }, { status: 400 });
  try {
    const root = process.cwd();
    const full = join(root, "content", p);
    const buf = await readFile(full);
    const ext = extname(full).toLowerCase();
    if (ext === ".json") {
      try {
        const json = JSON.parse(buf.toString());
        return NextResponse.json(json);
      } catch {
        return NextResponse.json({ error: "Invalid JSON" }, { status: 500 });
      }
    }
    return new NextResponse(buf.toString(), {
      status: 200,
      headers: { "Content-Type": "text/plain; charset=utf-8" },
    });
  } catch (e) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }
}
