import { graphql } from "@/gql";
import { GenericFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { Blocks } from "@/components/blocks/Blocks";
import { notFound } from "next/navigation";
import { PageHeader } from "@/components/general/PageHeader";

export const dynamicParams = false;

const GenericFragmentDefinition = graphql(`
  fragment Generic on GenericPage {
    __typename
    id
    urlPath
    title
    lead
    body {
      ...Blocks
    }
  }
`);

export async function generateStaticParams() {
  const allGenericSlugsQuery = graphql(`
    query allGenericSlugs {
      pages(contentType: "generic.GenericPage") {
        id
        urlPath
      }
    }
  `);
  const { data, error } = await getClient().query(allGenericSlugsQuery, {});

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

  return data?.pages.map((page: any) => {
    // wagtail-grapple prepends the home page slug to the full path on multisite setups
    // we also strip the trailing slash
    const urlPath: string[] = page.urlPath
      .replace(/\/home\//, "")
      .replace(/\/$/, "")
      .split("/");
    return {
      url: urlPath,
    };
  });
}

export default async function Page({ params }: { params: { url: string[] } }) {
  const { url } = params;
  // for the page /foo/bar we need to look for `/home/foo/bar/`
  const urlPath = `/home/${url.join("/")}/`;

  const genericPageByUrlPathQuery = graphql(`
    query genericPageByUrl($urlPath: String!) {
      page: page(contentType: "generic.GenericPage", urlPath: $urlPath) {
        ... on GenericPage {
          ...Generic
        }
      }
    }
  `);

  const { data, error } = await getClient().query(genericPageByUrlPathQuery, {
    urlPath: urlPath,
  });

  const page = (data?.page ?? []) as GenericFragment;

  if (!page) {
    return notFound();
  }

  return (
    <main className="site-main" id="main">
      <PageHeader heading={page.title} lead={page.lead} />
      <Blocks blocks={page.body} />
    </main>
  );
}
