// src/hooks/queries/usePriceHistoryQuery.ts
import { useQuery } from '@tanstack/react-query';
import { fetchHistoricalPriceData } from '../../services/apiClient';
import { queryKeys } from '../../config/queryKeys';
import type { HistoricalPriceDataPoint } from '../../types';

/**
 * Query hook for fetching historical price data for watched items.
 *
 * @param masterItemIds - Array of master item IDs to fetch history for
 * @param enabled - Whether the query should run (default: true when IDs provided)
 * @returns TanStack Query result with HistoricalPriceDataPoint array
 *
 * @example
 * ```tsx
 * const itemIds = watchedItems.map(item => item.master_grocery_item_id).filter(Boolean);
 * const { data: priceHistory = [], isLoading, error } = usePriceHistoryQuery(itemIds);
 * ```
 */
export const usePriceHistoryQuery = (masterItemIds: number[], enabled: boolean = true) => {
  return useQuery({
    queryKey: queryKeys.priceHistory(masterItemIds),
    queryFn: async (): Promise<HistoricalPriceDataPoint[]> => {
      if (masterItemIds.length === 0) {
        return [];
      }

      const response = await fetchHistoricalPriceData(masterItemIds);

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

      return response.json();
    },
    enabled: enabled && masterItemIds.length > 0,
    staleTime: 1000 * 60 * 10, // 10 minutes - historical data doesn't change frequently
  });
};
