---
import { getCollection } from 'astro:content';
import DocLayout from '@layouts/DocLayout.astro';
import { render } from 'astro:content';
import { buildBreadcrumbs } from '@utils/content';

export async function getStaticPaths() {
  const DEFAULT_VERSION = '5x';
  const VERSION_PREFIXES = ['5x', '4x', '3x'];

  const pages = await getCollection('docs');

  const paths: Array<{
    params: { lang: string; slug: string };
    props: { page: (typeof pages)[0]; version: string };
  }> = [];

  pages.forEach((page) => {
    const [lang, ...slugParts] = page.id.split('/');
    const fullSlug = slugParts.join('/');

    const isVersioned = VERSION_PREFIXES.some((v) => fullSlug.startsWith(`${v}/`));

    paths.push({
      params: { lang, slug: fullSlug },
      props: { page, version: isVersioned ? slugParts[0] : DEFAULT_VERSION },
    });
  });

  const defaultVersionPages = pages.filter((page) => {
    const [, ...slugParts] = page.id.split('/');
    return slugParts[0] === DEFAULT_VERSION;
  });

  defaultVersionPages.forEach((page) => {
    const [lang, , ...restSlugParts] = page.id.split('/');
    const nonVersionedSlug = restSlugParts.join('/');

    const exists = paths.some((p) => p.params.lang === lang && p.params.slug === nonVersionedSlug);

    if (!exists && nonVersionedSlug) {
      paths.push({
        params: { lang, slug: nonVersionedSlug },
        props: { page, version: DEFAULT_VERSION },
      });
    }
  });

  return paths;
}

const { page, version } = Astro.props;
const { lang, slug } = Astro.params;
const { Content } = await render(page);
const breadcrumbs = await buildBreadcrumbs(lang, slug, 'docs', version);
const { title, description } = page.data;
---

<DocLayout title={title} description={description} breadcrumbs={breadcrumbs}>
  <Content />
</DocLayout>
