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

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // 5 min
      gcTime: 24 * 60 * 60 * 1000, // 24h
      retry: (failureCount, error: any) => {
        if (error?.response?.status === 401) return false;
        return failureCount < 2;
      },
      networkMode: 'offlineFirst', // Enable offline-first mode
      refetchOnReconnect: true,
    },
    mutations: {
      retry: false,
      networkMode: 'offlineFirst', // Queue mutations when offline
    },
  },
});

// Persist query data for offline access
queryClient.setMutationDefaults(['tasks'], {
  mutationFn: async (variables: any) => {
    // This will be overridden by actual mutations
    return variables;
  },
  onSuccess: (data, variables, context) => {
    // Save successful query results for offline access
    const queryKey = (context as any)?.queryKey;
    if (queryKey) {
      offlineSyncManager.saveOfflineData(JSON.stringify(queryKey), data);
    }
  },
});
