import type { EnhancedAuthClient } from "@tailor-platform/app-shell";
import { useMemo } from "react";
import { Provider as UrqlProvider, createClient, cacheExchange, fetchExchange } from "urql";

interface GraphQLProviderProps {
  authClient: EnhancedAuthClient;
  children: React.ReactNode;
}

export const GraphQLProvider = ({ authClient, children }: GraphQLProviderProps) => {
  const client = useMemo(() => {
    const appUrl = import.meta.env.VITE_TAILOR_APP_URL as string | undefined;
    if (!appUrl) {
      throw new Error("VITE_TAILOR_APP_URL must be set");
    }
    const url = `${appUrl}/query`;

    return createClient({
      url,
      exchanges: [cacheExchange, fetchExchange],
      requestPolicy: "cache-first",
      preferGetMethod: false,
      fetch: authClient.fetch,
    });
  }, [authClient]);

  return <UrqlProvider value={client}>{children}</UrqlProvider>;
};
