import { getSegmentServiceV1 } from '../services'

import { useQuery } from '@tanstack/react-query'

interface UseSegmentsTotalRecipients {
  data: number | undefined
  isLoading: boolean
  isError: boolean
}

export function useSegmentsTotalRecipients(
  segmentIds: string[] | undefined | null,
  cutoff?: Date
): UseSegmentsTotalRecipients {
  const hasSegmentsToCount = Boolean(segmentIds && segmentIds.length > 0)

  return useQuery({
    queryKey: ['segments', segmentIds?.join(), 'total-recipients'],
    queryFn: () => {
      if (!segmentIds || segmentIds.length === 0) {
        return undefined
      }
      return getSegmentServiceV1().countMultiSegments(segmentIds, cutoff)
    },
    refetchOnWindowFocus: false, // do not refetch as this is an expensive query for large segments
    enabled: hasSegmentsToCount
  })
}
