import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

import { ToastContainer, toastHandler } from 'components';

import type {
	ContextOptions,
	QueryClientProviderProps,
} from '@tanstack/react-query';

const queryClient = new QueryClient({
	defaultOptions: {
		mutations: {
			onError: (error) => toastHandler({ error }),
		},
	},
});

export const QueryProvider = (props?: QueryProviderProps) => {
	const { children, client = queryClient, ...options } = props || {};

	return (
		<QueryClientProvider
			{...({ client, ...options } as QueryClientProviderProps)}
		>
			<ToastContainer />
			{children}
		</QueryClientProvider>
	);
};

// Re-declaring as interfaces since we gave up modifying the package types
interface QueryClientProviderPropsBase {
	client?: QueryClient;
	children?: React.ReactNode;
}

interface QueryClientProviderPropsWithContext
	extends ContextOptions,
		QueryClientProviderPropsBase {
	contextSharing?: never;
}

interface QueryClientProviderPropsWithContextSharing
	extends QueryClientProviderPropsBase {
	context?: never;
	contextSharing?: boolean;
}

type QueryProviderProps =
	| QueryClientProviderPropsWithContext
	| QueryClientProviderPropsWithContextSharing;

export default QueryProvider;
