// src/config/queryClient.ts
import { QueryClient } from '@tanstack/react-query';
import { logger } from '../services/logger.client';

/**
 * Global QueryClient instance for TanStack Query.
 *
 * Configured with sensible defaults for the flyer-crawler application:
 * - 5 minute stale time for most queries
 * - 30 minute garbage collection time
 * - Single retry attempt on failure
 * - No automatic refetch on window focus (to reduce API load)
 * - Refetch on component mount for fresh data
 *
 * @see https://tanstack.com/query/latest/docs/reference/QueryClient
 */
export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      // Data is considered fresh for 5 minutes
      staleTime: 1000 * 60 * 5,

      // Unused data is garbage collected after 30 minutes
      // (gcTime was formerly called cacheTime in v4)
      gcTime: 1000 * 60 * 30,

      // Retry failed requests once
      retry: 1,

      // Don't refetch on window focus to reduce API calls
      // Users can manually refresh if needed
      refetchOnWindowFocus: false,

      // Always refetch on component mount to ensure fresh data
      refetchOnMount: true,

      // Don't refetch on reconnect by default
      refetchOnReconnect: false,
    },
    mutations: {
      // Don't retry mutations automatically
      // User actions should be explicit
      retry: 0,

      // Log mutation errors for debugging
      onError: (error) => {
        logger.error('Mutation error', {
          error: error instanceof Error ? error.message : 'Unknown error',
        });
      },
    },
  },
});
