'use client';


import { useToast } from "../components/Toaster/useToast.mjs";
import { MutationCache, QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useRef } from "react";
import { jsx } from "react/jsx-runtime";

//#region src/providers/ReactQueryProvider.tsx
const defaultQueryOptions = {
	queries: {
		retry: 1,
		staleTime: 0,
		gcTime: 300 * 1e3,
		refetchOnMount: "always",
		refetchOnWindowFocus: false,
		refetchOnReconnect: false
	},
	mutations: { retry: 0 }
};
const formatErrorCode = (errorCode) => errorCode.split("_").join(" ");
/**
*  Hook to handle error logging and toast notifications
*/
const useToastEvents = () => {
	const { toast } = useToast();
	const onError = (error) => {
		[(() => {
			try {
				if (typeof error === "string") return JSON.parse(error);
			} catch (_) {}
			return error;
		})()].flat().forEach((err) => {
			toast({
				title: formatErrorCode((process.env.NODE_ENV === "production" ? err?.title : err?.code) ?? "Error"),
				description: err?.message ?? String(err ?? "An error occurred"),
				variant: "error"
			});
		});
	};
	const onSuccess = (data) => {
		if (data?.error) toast({
			title: formatErrorCode(data.error.title ?? data.error.code ?? "Error"),
			description: data.error.message ?? data.error.code ?? "An error occurred",
			variant: "error"
		});
		if (data?.message) toast({
			title: data.message,
			description: data.description,
			variant: "success"
		});
	};
	return {
		onError,
		onSuccess
	};
};
const ReactQueryProvider = ({ children }) => {
	const { onError, onSuccess } = useToastEvents();
	const clientRef = useRef(null);
	if (!clientRef.current) {
		const queryClient = new QueryClient({
			defaultOptions: defaultQueryOptions,
			mutationCache: new MutationCache({
				onSuccess,
				onError,
				onSettled: (_data, _error, _variables, _context, mutation) => {
					if (mutation.meta?.invalidateQueries) mutation.meta.invalidateQueries.forEach((queryKey) => {
						queryClient.invalidateQueries({ queryKey });
					});
					if (mutation.meta?.resetQueries) mutation.meta.resetQueries.forEach((queryKey) => {
						queryClient.resetQueries({ queryKey });
					});
				}
			})
		});
		clientRef.current = queryClient;
	}
	return /* @__PURE__ */ jsx(QueryClientProvider, {
		client: clientRef.current,
		children
	});
};

//#endregion
export { ReactQueryProvider };
//# sourceMappingURL=ReactQueryProvider.mjs.map