import {useQueryFetchIfEmpty} from '@hooks/queries/useQueryFetchIfEmpty';
import {useInstanceId} from '@redux/selectors';
import {getInstanceTotalUsers} from '@services/instance';
import {getUsersAudienceCount} from '@services/user';

import {newPostQueryKeys} from '../constants';

export const useGetSegmentationUsersCount = ({
  selectedSegmentationItemIds,
}: {
  selectedSegmentationItemIds: number[];
}) => {
  const instanceId = useInstanceId();
  const {data: allUsersCount} = useQueryFetchIfEmpty(
    newPostQueryKeys.totalUsers,
    () => getInstanceTotalUsers(instanceId),
    {
      enabled: !!instanceId && !selectedSegmentationItemIds.length,
      initialData: 0,
    },
  );

  const {data: segmentationCount} = useQueryFetchIfEmpty(
    newPostQueryKeys.segmentationUsersCount(selectedSegmentationItemIds),
    () =>
      getUsersAudienceCount({
        segmentationItemIds: selectedSegmentationItemIds.join(','),
        includeLoggedUser: true,
      }),
    {
      enabled: !!(instanceId && selectedSegmentationItemIds.length),
      keepPreviousData: true,
    },
  );

  return selectedSegmentationItemIds.length
    ? segmentationCount?.count
    : allUsersCount;
};
