import { getClient } from "@/app/client";
import { NewsList } from "@/components/news/NewsList";
import { Metadata, ResolvingMetadata } from "next";
import { PageHeader } from "@/components/general/PageHeader";
import { newsQuery, NewsFragment, NewsIndexFragment } from "@/lib/news";
import { getSeoMetadata } from "@/lib/seo";

export async function generateMetadata(
  { params }: { params: Promise<{}> },
  parent: ResolvingMetadata
): Promise<Metadata | null> {
  const { data, error } = await getClient().query(newsQuery, {});
  if (error) {
    throw new Error(error.message);
  }
  if (!data?.index) {
    return null;
  }

  const index = data.index as NewsIndexFragment;
  const metadata = await getSeoMetadata(index, parent);
  return metadata;
}

export default async function Page() {
  const { data, error } = await getClient().query(newsQuery, {});
  if (error) {
    throw new Error(error.message);
  }
  const news = (data?.news ?? []) as NewsFragment[];
  const index = data?.index as NewsIndexFragment;

  return (
    <main className="site-main" id="main">
      <PageHeader heading={index.title} lead={index.lead} align="left" />
      <NewsList news={news} />
    </main>
  );
}
