// src/providers/FlyersProvider.tsx
import React, { ReactNode } from 'react';
import { FlyersContext, FlyersContextType } from '../contexts/FlyersContext';
import type { Flyer } from '../types';
import * as apiClient from '../services/apiClient';
import { useInfiniteQuery } from '../hooks/useInfiniteQuery';
import { useCallback } from 'react';

export const FlyersProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  // Memoize the fetch function to ensure stability for the useInfiniteQuery hook.
  const fetchFlyersFn = useCallback(apiClient.fetchFlyers, []);

  const {
    data: flyers,
    isLoading: isLoadingFlyers,    
    error: flyersError,
    fetchNextPage: fetchNextFlyersPage,
    hasNextPage: hasNextFlyersPage,
    refetch: refetchFlyers,
    isRefetching: isRefetchingFlyers,
  } = useInfiniteQuery<Flyer>(fetchFlyersFn);

  const value: FlyersContextType = {
    flyers: flyers || [],
    isLoadingFlyers,
    flyersError,
    fetchNextFlyersPage,
    hasNextFlyersPage,
    isRefetchingFlyers,
    refetchFlyers,
  };

 return <FlyersContext.Provider value={value}>{children}</FlyersContext.Provider>;
};
