import { Metadata, ResolvingMetadata } from "next";
import { notFound } from "next/navigation";
import { getClient } from "@/app/client";
import {
  NewsPageView,
  loadNewsPageProps,
} from "@/components/news/NewsPageView";
import { graphql } from "@/gql";
import { getSeoMetadata } from "@/lib/seo";

export async function generateStaticParams() {
  const allNewsSlugsQuery = graphql(`
    query allNewsSlugs {
      pages(contentType: "news.NewsPage") {
        id
        slug
      }
    }
  `);
  const { data, error } = await getClient().query(allNewsSlugsQuery, {});

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

  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 loadNewsPageProps({ slug });
  if (!props) return null;
  return getSeoMetadata(props.news, parent);
}

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