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

export function useAgentMetrics(
  agentId: string | null,
  names: string[],
  buckets = 60,
  from?: string,
  to?: string,
  mode: 'gauge' | 'delta' = 'gauge',
) {
  const environment = useEnvironmentStore((s) => s.environment);
  const refetchInterval = useRefreshInterval(30_000);
  return useQuery({
    queryKey: ['agent-metrics', environment, agentId, names.join(','), buckets, from, to, mode],
    queryFn: async () => {
      const token = useAuthStore.getState().accessToken;
      const params = new URLSearchParams({
        names: names.join(','),
        buckets: String(buckets),
        mode,
      });
      if (from) params.set('from', from);
      if (to) params.set('to', to);
      const res = await fetch(
        `${config.apiBaseUrl}/environments/${encodeURIComponent(environment!)}/agents/${encodeURIComponent(agentId!)}/metrics?${params}`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
            'X-Cameleer-Protocol-Version': '1',
          },
        });
      if (!res.ok) throw new Error(`${res.status}`);
      return res.json() as Promise<{ metrics: Record<string, Array<{ time: string; value: number }>> }>;
    },
    enabled: !!agentId && names.length > 0 && !!environment,
    refetchInterval,
  });
}
