// src/providers/FlyersProvider.tsx
import React, { ReactNode, useMemo } from 'react';
import { FlyersContext, FlyersContextType } from '../contexts/FlyersContext';
import { useFlyersQuery } from '../hooks/queries/useFlyersQuery';

/**
 * Provider for flyer data using TanStack Query (ADR-0005).
 *
 * This replaces the previous custom useInfiniteQuery implementation with
 * TanStack Query for better caching, automatic refetching, and state management.
 *
 * Note: Currently fetches all flyers (no pagination UI). Infinite scroll can be
 * added later when the backend API returns proper pagination metadata.
 */
export const FlyersProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  // Fetch all flyers with a large limit (effectively "all")
  // TODO: Implement proper infinite scroll when backend API is updated
  const {
    data: flyers,
    isLoading: isLoadingFlyers,
    error,
    refetch: refetchFlyers,
    isRefetching: isRefetchingFlyers,
  } = useFlyersQuery(1000, 0);

  const value: FlyersContextType = useMemo(
    () => ({
      flyers: flyers || [],
      isLoadingFlyers,
      flyersError: error,
      // Stub methods for compatibility with existing code
      // TODO: Remove these when infinite scroll is properly implemented
      fetchNextFlyersPage: () => {},
      hasNextFlyersPage: false,
      isRefetchingFlyers,
      refetchFlyers,
    }),
    [flyers, isLoadingFlyers, error, isRefetchingFlyers, refetchFlyers]
  );

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