import { ParsedUrlQuery } from "querystring";

import { GetStaticPaths, GetStaticProps } from "next";
import { MDXRemote } from "next-mdx-remote";
import React from "react";

import { EventCard } from "@/components/EventCard";
import {
  Event,
  getEventYears,
  getEventTermsByYear,
  getEventsByTerm,
  getEventBySlug,
} from "@/lib/events";

export default function EventInfoPage(props: Props) {
  return (
    <EventCard
      {...props.event.metadata}
      date={new Date(props.event.metadata.date)}
    >
      <MDXRemote {...props.event.content} />
    </EventCard>
  );
}

interface Props {
  event: Event;
}

interface Params extends ParsedUrlQuery {
  year: string;
  term: string;
  event: string;
}

export const getStaticProps: GetStaticProps<Props, Params> = async (
  context
) => {
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  const { year, term, event } = context.params!;
  return { props: { event: await getEventBySlug(year, term, event) } };
};

export const getStaticPaths: GetStaticPaths<Params> = async () => {
  const years = await getEventYears();
  const events = (
    await Promise.all(
      years.map(async (year) => {
        const termsInYear = await getEventTermsByYear(year);
        return await Promise.all(
          termsInYear.map(async (term) => {
            const eventsInTerm = await getEventsByTerm(year, term);
            return eventsInTerm.map((event) => ({
              year,
              term,
              event,
            }));
          })
        );
      })
    )
  ).flat(2);

  return {
    paths: events.map((params) => ({ params })),
    fallback: false,
  };
};
