import { promises as fs } from "fs";
import path from "path";

import { getDocumentsBaseDir } from "@/lib/server/local-paths";

export const dynamic = "force-dynamic";

function contentTypeByExt(file: string): string {
  const ext = path.extname(file).toLowerCase();
  if (ext === ".md") return "text/markdown; charset=utf-8";
  if (ext === ".json") return "application/json; charset=utf-8";
  if (ext === ".txt") return "text/plain; charset=utf-8";
  return "application/octet-stream";
}

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ id: string; filePath: string[] }> },
) {
  const { id, filePath } = await params;
  if (!id || !Array.isArray(filePath) || filePath.length === 0) {
    return new Response("Not Found", { status: 404 });
  }

  const baseDir = path.resolve(getDocumentsBaseDir(), id);
  const resolved = path.resolve(baseDir, ...filePath);
  if (!resolved.startsWith(baseDir + path.sep)) {
    return new Response("Bad Request", { status: 400 });
  }

  try {
    const buf = await fs.readFile(resolved);
    return new Response(buf, {
      headers: {
        "Content-Type": contentTypeByExt(resolved),
        "Cache-Control": "no-store",
      },
    });
  } catch {
    return new Response("Not Found", { status: 404 });
  }
}

