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

function getWagtailUrlPath(url: string[]): string {
  // for the page /foo/bar we need to look for `/home/foo/bar/`
  return `/home/${url.join("/")}/`;
}

export async function generateStaticParams() {
  const allGenericSlugsQuery = graphql(`
    query allGenericSlugs {
      pages(contentType: "generic.GenericPage") {
        id
        urlPath
      }
    }
  `);
  const { data, error } = await getClient().query(allGenericSlugsQuery, {});
  if (error) {
    throw new Error(error.message);
  }
  if (!data?.pages) {
    throw new Error("Failed to generate static params for generic subpages");
  }

  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,
    };
  });
}

type Params = Promise<{ url: string[] }>;

export async function generateMetadata(
  { params }: { params: Params },
  parent: ResolvingMetadata
): Promise<Metadata | null> {
  const { url } = await params;
  const props = await loadGenericPageProps({ urlPath: getWagtailUrlPath(url) });
  if (!props) return null;
  return getSeoMetadata(props.page, parent);
}

export default async function Page({ params }: { params: Params }) {
  const { url } = await params;
  const props = await loadGenericPageProps({ urlPath: getWagtailUrlPath(url) });
  if (!props) return notFound();
  return <GenericPageView {...props} />;
}
