import { useQuery } from 'react-query';

import { type SegmentationExpressionPayload } from '@material-hu/components/composed-components/audience/types';

import { librariesKeys } from '../queries';
import { countAudienceByExpression } from '../services';

/**
 * Fetches the audience count for a given segmentation expression.
 * Automatically refetches when the expression changes.
 */
const useGetAudienceCount = (
  expression: SegmentationExpressionPayload | null,
  key?: number,
) =>
  useQuery({
    queryKey: [...librariesKeys.audience.count(expression), key],
    queryFn: () => {
      if (!expression) {
        throw new Error('[useGetAudienceCount] Expression is required');
      }
      return countAudienceByExpression({
        segmentationExpression: expression,
      });
    },
    select: response => response.data.count,
    enabled: !!expression && expression.conditions.length > 0,
  });

export default useGetAudienceCount;
