import { Metadata, ResolvingMetadata } from "next";
import { notFound } from "next/navigation";
import { getClient } from "@/app/client";
import {
  AssociationPageView,
  loadAssociationPageProps,
} from "@/components/associations/AssociationPageView";
import { graphql } from "@/gql";
import { getSeoMetadata } from "@/lib/seo";

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

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

export async function generateStaticParams() {
  const allAssociationSlugsQuery = graphql(`
    query allAssociationSlugs {
      pages(contentType: "associations.AssociationPage") {
        id
        slug
      }
    }
  `);
  const { data, error } = await getClient().query(allAssociationSlugsQuery, {});

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

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

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