import { ParsedUrlQuery } from "querystring";

import { GetStaticPaths, GetStaticProps, GetStaticPropsContext } from "next";

import { createReadAllSection } from "@/components/OrganizedContent";
import {
  getSectionNamesForPage,
  getSectionsForPage,
} from "@/lib/organized-content";

import { Props as ReadAllProps } from "./ReadAll";
import { Props as SectionProps } from "./Section";

export function createReadAllGetStaticProps(pagePath: string) {
  return (async () => {
    const sections = await getSectionsForPage(pagePath);

    return {
      props: {
        sections: sections.map(({ name: id, data: { title, content } }) => ({
          section: {
            id,
            title,
          },
          content,
        })),
      },
    };
  }) as GetStaticProps<ReadAllProps>;
}

interface SectionParams extends ParsedUrlQuery {
  section: string;
}

export function createSectionGetStaticProps(pagePath: string) {
  return async function getStaticProps(
    context: GetStaticPropsContext<SectionParams>
  ) {
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    const currentName = context.params!.section;
    const fullSections = await getSectionsForPage(pagePath);
    const current = fullSections.findIndex(({ name }) => name === currentName);

    const sections = fullSections.map(({ name, data: { title } }) => ({
      id: name,
      title,
    }));

    return {
      props: {
        content: fullSections[current].data.content,
        current: current + 1,
        sections: [createReadAllSection(sections, false), ...sections],
      },
    };
  } as GetStaticProps<SectionProps, SectionParams>;
}

export function createSectionGetStaticPaths(pagePath: string) {
  return async function getStaticPaths() {
    const names = await getSectionNamesForPage(pagePath);

    return {
      paths: names.map((section) => ({ params: { section } })),
      fallback: false,
    };
  } as GetStaticPaths<SectionParams>;
}
