import { getClient } from "@/app/client";
import { Blocks } from "@/components/blocks/Blocks";
import { EventDetails } from "@/components/events/EventDetails";
import { EventHeader } from "@/components/events/EventHeader";
import { BgPig } from "@/components/general/BgPig";
import { graphql } from "@/gql";
import { EventFragment } from "@/gql/graphql";
import { getEventPig } from "@/lib/event";
import { notFound } from "next/navigation";

export async function generateStaticParams() {
  const allEventSlugsQuery = graphql(`
    query allEventSlugs {
      pages(contentType: "events.EventPage") {
        id
        slug
      }
    }
  `);
  const { data, error } = await getClient().query(allEventSlugsQuery, {});

  if (data === undefined || error) {
    throw new Error("failed to generate static params");
  }

  return data?.pages.map((page: any) => ({
    slug: page.slug,
  }));
}

export default async function Page({ params }: { params: { slug: string } }) {
  const eventBySlugQuery = graphql(`
    query eventBySlug($slug: String!) {
      event: page(contentType: "events.EventPage", slug: $slug) {
        ... on EventPage {
          ...Event
        }
      }
    }
  `);

  const { data, error } = await getClient().query(eventBySlugQuery, {
    slug: params.slug,
  });

  if (data?.event === null || error) {
    return notFound();
  }

  const event = (data?.event ?? {}) as EventFragment;
  const eventPig = getEventPig(event);

  return (
    <>
      <main className="site-main" id="main">
        <EventHeader event={event} />
        <EventDetails event={event} />
        <section className="pageContent">
          <Blocks blocks={event.body} />
        </section>
      </main>
      {eventPig && <BgPig type={eventPig} color="white" />}
    </>
  );
}
