import { useQuery } from '@tanstack/react-query';
import { config as appConfig } from '../../config';
import { useAuthStore } from '../../auth/auth-store';

export function useCorrelationChain(correlationId: string | null, environment?: string) {
  return useQuery({
    queryKey: ['correlation-chain', environment, correlationId],
    queryFn: async () => {
      const token = useAuthStore.getState().accessToken;
      const res = await fetch(
        `${appConfig.apiBaseUrl}/environments/${encodeURIComponent(environment!)}/executions/search`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            ...(token ? { Authorization: `Bearer ${token}` } : {}),
            'X-Cameleer-Protocol-Version': '1',
          },
          body: JSON.stringify({
            correlationId: correlationId!,
            limit: 20,
            sortField: 'startTime',
            sortDir: 'asc',
          }),
        });
      if (!res.ok) throw new Error('Failed to load correlation chain');
      return res.json();
    },
    enabled: !!correlationId && !!environment,
  });
}
