import { graphql } from "@/gql";
import { ContactIndexFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { GeneralContactBlock } from "@/components/blocks/GeneralContactBlock";
import { PageContent } from "@/components/general/PageContent";
import { PageHeader } from "@/components/general/PageHeader";

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

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

export type ContactIndexViewProps = { index: ContactIndexFragment };

export async function loadContactIndexProps(overrides?: {
  indexOverride?: ContactIndexFragment;
}): Promise<ContactIndexViewProps> {
  if (overrides?.indexOverride) {
    return { index: overrides.indexOverride };
  }
  const { data, error } = await getClient().query(contactQuery, {});
  if (error) throw new Error(error.message);
  const index = data?.index as ContactIndexFragment | undefined;
  if (!index) throw new Error("Failed to load /kontakt");
  return { index };
}

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