// the address bar's search index: every page, its headings, and (on configuration) its settings

import type { APIRoute } from "astro";
import { loadDocs } from "../lib/docs";
import { iconId } from "../lib/icons";

// how the setting is spelled in an env file, from configuration.md: everything has the prefix but RUST_LOG
const envKey = (key: string) => (key === "RUST_LOG" ? key : `HYDRANT_${key}`);

export const GET: APIRoute = async () => {
  const docs = await loadDocs();
  const entries = [...docs.values()].flatMap((doc) => {
    const { section, label, icon } = doc.place;
    const page = label === "overview" ? `${section.title} overview` : label;
    return [
      { kind: "page", label: page, hint: section.title, url: doc.url, icon: iconId(icon) },
      ...doc.headings
        .filter((h) => h.depth >= 2 && h.depth <= 3)
        .map((h) => ({ kind: "heading", label: h.text, hint: page, url: `${doc.url}#${h.id}`, icon: iconId(icon) })),
      ...(doc.settings ?? []).flatMap((s) =>
        s.settings.map((st) => ({ kind: "setting", label: envKey(st.key), hint: `${page} › ${s.title}`, url: `${doc.url}#${st.key}`, icon: iconId(icon) })),
      ),
    ];
  });
  return new Response(JSON.stringify(entries), { headers: { "content-type": "application/json" } });
};
