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

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

export const dynamic = "force-dynamic";

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

  const baseDir = path.resolve(getLegacyMindmapsBaseDir(), docId);
  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);
    const ext = path.extname(resolved).toLowerCase();
    const contentType =
      ext === ".json"
        ? "application/json; charset=utf-8"
        : "application/octet-stream";
    return new Response(buf, {
      headers: { "Content-Type": contentType, "Cache-Control": "no-store" },
    });
  } catch {
    return new Response("Not Found", { status: 404 });
  }
}

