// src/hooks/queries/useFlyersQuery.ts
import { useQuery } from '@tanstack/react-query';
import * as apiClient from '../../services/apiClient';
import { queryKeys } from '../../config/queryKeys';
import type { Flyer } from '../../types';

/**
 * Query hook for fetching flyers with pagination.
 *
 * This replaces the custom useInfiniteQuery hook with TanStack Query,
 * providing automatic caching, background refetching, and better state management.
 *
 * @param limit - Maximum number of flyers to fetch
 * @param offset - Number of flyers to skip
 * @returns Query result with flyers data, loading state, and error state
 *
 * @example
 * ```tsx
 * const { data: flyers, isLoading, error, refetch } = useFlyersQuery(20, 0);
 * ```
 */
export const useFlyersQuery = (limit: number = 20, offset: number = 0) => {
  return useQuery({
    queryKey: queryKeys.flyers(limit, offset),
    queryFn: async (): Promise<Flyer[]> => {
      const response = await apiClient.fetchFlyers(limit, offset);

      if (!response.ok) {
        const error = await response.json().catch(() => ({
          message: `Request failed with status ${response.status}`,
        }));
        throw new Error(error.message || 'Failed to fetch flyers');
      }

      const json = await response.json();
      // ADR-028: API returns { success: true, data: [...] }
      // If success is false or data is not an array, return empty array to prevent .map() errors
      if (!json.success || !Array.isArray(json.data)) {
        return [];
      }
      return json.data;
    },
    // Keep data fresh for 2 minutes since flyers don't change frequently
    staleTime: 1000 * 60 * 2,
  });
};
