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

/**
 * Query hook for fetching items for a specific flyer.
 *
 * This hook is automatically disabled when no flyer ID is provided,
 * and caches data per-flyer to avoid refetching the same data.
 *
 * @param flyerId - The ID of the flyer to fetch items for
 * @returns Query result with flyer items data, loading state, and error state
 *
 * @example
 * ```tsx
 * const { data: flyerItems, isLoading, error } = useFlyerItemsQuery(flyer?.flyer_id);
 * ```
 */
export const useFlyerItemsQuery = (flyerId: number | undefined) => {
  return useQuery({
    queryKey: queryKeys.flyerItems(flyerId as number),
    queryFn: async (): Promise<FlyerItem[]> => {
      if (!flyerId) {
        throw new Error('Flyer ID is required');
      }

      const response = await apiClient.fetchFlyerItems(flyerId);

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

      const data = await response.json();
      // API returns { items: FlyerItem[] }
      return data.items || [];
    },
    // Only run the query if we have a valid flyer ID
    enabled: !!flyerId,
    // Flyer items don't change, so cache them longer
    staleTime: 1000 * 60 * 5,
  });
};
