// src/hooks/useFlyerItems.ts
import type { Flyer, FlyerItem } from '../types';
import { useApiOnMount } from './useApiOnMount';
import * as apiClient from '../services/apiClient';

/**
 * A custom hook to fetch the items for a given flyer.
 * @param selectedFlyer The flyer for which to fetch items.
 * @returns An object containing the flyer items, loading state, and any errors.
 */
export const useFlyerItems = (selectedFlyer: Flyer | null) => {
  const wrappedFetcher = (flyerId?: number): Promise<Response> => {
    // This should not be called with undefined due to the `enabled` flag,
    // but this wrapper satisfies the type checker.
    if (flyerId === undefined) {
      return Promise.reject(new Error("Cannot fetch items for an undefined flyer ID."));
    }
    return apiClient.fetchFlyerItems(flyerId);
  };

  const { data, loading, error } = useApiOnMount<{ items: FlyerItem[] }, [number?]>(
    wrappedFetcher,
    [selectedFlyer],
    { enabled: !!selectedFlyer },
    selectedFlyer?.flyer_id
  );
  return { flyerItems: data?.items || [], isLoading: loading, error };
};