import type { APIRoute } from "astro";
import * as fs from "node:fs/promises";
import * as path from "node:path";

export const prerender = true;

async function exists(p: string) {
  try { await fs.access(p); return true; } catch { return false; }
}

export const GET: APIRoute = async () => {
  const distFile = path.join(process.cwd(), "dist", "para-index.json");

  // Si dist existe (ex: après un build), on renvoie le vrai fichier.
  if (await exists(distFile)) {
    const raw = await fs.readFile(distFile, "utf8");
    return new Response(raw, {
      status: 200,
      headers: {
        "content-type": "application/json; charset=utf-8",
        "cache-control": "no-store",
      },
    });
  }

  // Sinon stub (dev sans build) : pas d’erreur, pas de crash, pas de 404.
  const stub = {
    schema: 1,
    generatedAt: new Date().toISOString(),
    items: [],
    byId: {},
    note: "para-index not built yet (run: npm run build to generate dist/para-index.json)",
  };

  return new Response(JSON.stringify(stub), {
    status: 200,
    headers: {
      "content-type": "application/json; charset=utf-8",
      "cache-control": "no-store",
    },
  });
};