import { Metadata, ResolvingMetadata } from "next";
import { notFound } from "next/navigation";
import { getClient } from "@/app/client";
import {
  EventPageView,
  loadEventPageProps,
} from "@/components/events/EventPageView";
import { graphql } from "@/gql";
import { getSeoMetadata } from "@/lib/seo";

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

  if (error) {
    throw new Error(error.message);
  }
  if (!data?.pages) {
    throw new Error(
      "Failed to generate static params for subpages of /arrangementer"
    );
  }

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

type Params = Promise<{ slug: string }>;

export async function generateMetadata(
  { params }: { params: Params },
  parent: ResolvingMetadata
): Promise<Metadata | null> {
  const { slug } = await params;
  const props = await loadEventPageProps({ slug });
  if (!props) return null;
  return getSeoMetadata(props.event, parent);
}

export default async function Page({ params }: { params: Params }) {
  const { slug } = await params;
  const props = await loadEventPageProps({ slug });
  if (!props) return notFound();
  return <EventPageView {...props} />;
}
