---
import type { DocsEntry, MenuItem } from "@/types";
import EntryLayout from "@components/docs/EntryLayout.astro";
import CollectionLayout from "@components/docs/CollectionLayout.astro";
import { getEntries, getEntriesInGroup, getGroups } from "@lib/contentParser";
import { sortByTitle } from "@lib/sortFunctions";

export async function getStaticPaths() {
  const entries = (await getEntries("docs", sortByTitle)) as DocsEntry[];

  const paths = entries.map((entry) => {
    const segments = entry.id.replace("/-index", "").split("/");

    if (segments.length === 1) {
      return {
        params: { id: segments[0] },
        props: { entry, isGroup: true },
      };
    } else if (segments.length === 2) {
      return {
        params: { id: entry.id },
        props: { entry, isGroup: false },
      };
    }
  });

  return paths;
}

const { entry, isGroup } = Astro.props;
const groupName = entry.id.replace("/-index", "");
const groupEntries = isGroup
  ? ((await getEntriesInGroup("docs", groupName, sortByTitle)) as DocsEntry[])
  : [];

// Construct Doc Browser menu
const browserMenu: MenuItem[] = [];
const groups = (await getGroups("docs", sortByTitle)) as DocsEntry[];
await Promise.all(
  groups.map(async (group) => {
    const groupEntries = (await getEntriesInGroup(
      "docs",
      group.id.replace("/-index", ""),
      sortByTitle
    )) as DocsEntry[];
    browserMenu.push({
      title: group.data.title,
      id: group.id.replace("/-index", ""),
      children: groupEntries.map((groupEntry) => ({
        title: groupEntry.data.title,
        id: groupEntry.id,
        children: [],
      })),
    });
  })
);
---

{
  isGroup ? (
    <CollectionLayout collectionIndex={entry} entries={groupEntries} />
  ) : (
    <EntryLayout entry={entry} browserMenu={browserMenu} />
  )
}
