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

const associationBySlugQuery = graphql(`
  query associationBySlug($slug: String!) {
    association: page(
      contentType: "associations.AssociationPage"
      slug: $slug
    ) {
      ... on AssociationPage {
        ...Association
      }
    }
  }
`);

export async function generateMetadata(
  { params }: { params: { slug: string } },
  parent: ResolvingMetadata
): Promise<Metadata | null> {
  const { data, error } = await getClient().query(associationBySlugQuery, {
    slug: params.slug,
  });

  if (error) {
    throw new Error(error.message);
  }
  if (!data?.association) {
    return null;
  }

  const association = data.association as AssociationFragment;
  const metadata = await getSeoMetadata(association, parent);
  return metadata;
}

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: { slug: string } }) {
  const { data, error } = await getClient().query(associationBySlugQuery, {
    slug: params.slug,
  });

  if (error) {
    throw new Error(error.message);
  }
  if (!data?.association) {
    return notFound();
  }

  const association = data.association as AssociationFragment;

  return (
    <main className="site-main" id="main">
      <AssociationHeader association={association} />
      <PageContent blocks={association.body} />
    </main>
  );
}
