import { graphql } from "@/gql";
import { AssociationFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { AssociationHeader } from "@/components/associations/AssociationHeader";
import { PageContent } from "@/components/general/PageContent";

const associationBySlugQuery = graphql(`
  query associationBySlug($slug: String!) {
    association: page(
      contentType: "associations.AssociationPage"
      slug: $slug
    ) {
      ... on AssociationPage {
        ...Association
      }
    }
  }
`);

export type AssociationPageViewProps = { association: AssociationFragment };

export async function loadAssociationPageProps(args: {
  slug?: string;
  associationOverride?: AssociationFragment;
}): Promise<AssociationPageViewProps | null> {
  if (args.associationOverride) {
    return { association: args.associationOverride };
  }
  if (!args.slug) throw new Error("loadAssociationPageProps needs slug or associationOverride");
  const { data, error } = await getClient().query(associationBySlugQuery, {
    slug: args.slug,
  });
  if (error) throw new Error(error.message);
  const association = data?.association as AssociationFragment | undefined;
  if (!association) return null;
  return { association };
}

export function AssociationPageView({ association }: AssociationPageViewProps) {
  return (
    <main className="site-main" id="main">
      <AssociationHeader association={association} />
      <PageContent blocks={association.body} />
    </main>
  );
}
