import "server-only";

import { cacheExchange, createClient, fetchExchange } from "@urql/core";
import { registerUrql } from "@urql/next/rsc";

import { CMS_CACHE_TAG } from "@/lib/revalidation";

const wagtailBaseUrl = process.env.WAGTAIL_BASE_URL;
if (!wagtailBaseUrl) {
  throw new Error("WAGTAIL_BASE_URL is not set");
}
const graphqlEndpoint = `${wagtailBaseUrl.replace(/\/$/, "")}/api/graphql/`;

const makeClient = () => {
  return createClient({
    url: graphqlEndpoint,
    exchanges: [cacheExchange, fetchExchange],
    // Cache all queries in the Data Cache until revalidateTag(CMS_CACHE_TAG);
    // override per operation with the contexts in @/lib/revalidation
    fetchOptions: { cache: "force-cache", next: { tags: [CMS_CACHE_TAG] } },
  });
};

export const { getClient } = registerUrql(makeClient);
