import { useQuery } from '@tanstack/react-query';
import { useOrderFilters } from './useOrderFilters';
import { orderService } from '../api/order.service';
import { OrderFilters } from '../schemas/order.schema';
import { omitBy, isNil } from 'lodash';

const normalizeFilters = (filters: Record<string, any>): OrderFilters => {
  const { searchTriggered, ...rest } = filters;
  const normalized = omitBy(rest, isNil);
  return normalized as OrderFilters;
};

export function useOrders() {
  const [filters] = useOrderFilters();
  const normalizedFilters = normalizeFilters(filters);
  const shouldSearch = filters.searchTriggered === true;

  return useQuery({
    queryKey: ['orders', normalizedFilters],
    enabled: shouldSearch && Object.keys(normalizedFilters).length > 0,
    queryFn: () => orderService.findOrders(normalizedFilters),
    staleTime: 1000 * 60 * 5,
    retry: 1,
    retryOnMount: false,
    refetchOnWindowFocus: false,
  });
}
