import { Metadata, ResolvingMetadata } from "next";
import { notFound } from "next/navigation";
import { graphql } from "@/gql";
import { ContactIndexFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { PageHeader } from "@/components/general/PageHeader";
import { PageContent } from "@/components/general/PageContent";
import { GeneralContactBlock } from "@/components/blocks/GeneralContactBlock";
import { getSeoMetadata } from "@/lib/seo";

const contactQuery = graphql(`
  query contacts {
    index: contactIndex {
      ... on ContactIndex {
        ...ContactIndex
      }
    }
  }
`);

const ContactIndexDefinition = graphql(`
  fragment ContactIndex on ContactIndex {
    ... on ContactIndex {
      title
      seoTitle
      searchDescription
      lead
      body {
        ...Blocks
      }
    }
  }
`);

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

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

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

export default async function Page() {
  const { data, error } = await getClient().query(contactQuery, {});

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

  const index = data.index as ContactIndexFragment;

  return (
    <main className="site-main" id="main">
      <PageHeader heading={index.title} lead={index.lead} />
      <GeneralContactBlock />
      {index.body && <PageContent blocks={index.body} />}
    </main>
  );
}
