import { useQuery } from '@tanstack/react-query';
import { config } from '../../config';
import { useAuthStore } from '../../auth/auth-store';
import { useRefreshInterval } from './use-refresh-interval';

export function useProcessorMetrics(routeId: string | null, appId?: string, environment?: string) {
  const refetchInterval = useRefreshInterval(30_000);
  return useQuery({
    queryKey: ['processor-metrics', environment, routeId, appId],
    queryFn: async () => {
      const token = useAuthStore.getState().accessToken;
      const params = new URLSearchParams();
      if (routeId) params.set('routeId', routeId);
      if (appId) params.set('appId', appId);
      const res = await fetch(
        `${config.apiBaseUrl}/environments/${encodeURIComponent(environment!)}/routes/metrics/processors?${params}`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
            'X-Cameleer-Protocol-Version': '1',
          },
        });
      if (!res.ok) throw new Error(`${res.status}`);
      return res.json();
    },
    enabled: !!routeId && !!environment,
    refetchInterval,
  });
}
