import { QueryClient } from '@tanstack/react-query';
import { ApiError } from './ApiError';

const DEFAULT_STALE_MILLISECONDS = 15000;
const MAXIMUM_RETRIES = 1;
const FIRST_CLIENT_ERROR_STATUS = 400;
const FIRST_SERVER_ERROR_STATUS = 500;

function isRefusedByServer( error: Error ): boolean {
	return (
		error instanceof ApiError &&
		error.httpStatus >= FIRST_CLIENT_ERROR_STATUS &&
		error.httpStatus < FIRST_SERVER_ERROR_STATUS
	);
}

function shouldRetryQuery( failureCount: number, error: Error ): boolean {
	return failureCount < MAXIMUM_RETRIES && ! isRefusedByServer( error );
}

export function createQueryClient(): QueryClient {
	return new QueryClient( {
		defaultOptions: {
			queries: {
				staleTime: DEFAULT_STALE_MILLISECONDS,
				retry: shouldRetryQuery,
			},
		},
	} );
}
