import { getCampaignSDK, getPhoneNumberService } from "services";

import {
  CountQueryParameters,
  PaginationQueryParameters,
  useOffsetPagination,
} from "hooks/usePagination";

import { CampaignType, PaginationDirection } from "@komi-app/messaging-sdk";

import { useQuery } from "@tanstack/react-query";

export function useOmniChannelCampaignsList(
  talentProfileId: string | undefined,
  searchTerm: string,
) {
  const safeFetchStats = async (campaignId: string) => {
    try {
      const { stats } =
        await getCampaignSDK().email.getCampaignAnalytics(campaignId);

      if (!stats) return { clickRate: undefined, openRate: undefined };
      const { processed, uniqueClicked, uniqueOpened } = stats;

      const openRate = (uniqueOpened * 100) / processed;
      const clickRate = (uniqueClicked * 100) / processed;

      return { clickRate, openRate };
    } catch (error) {
      return { clickRate: undefined, openRate: undefined };
    }
  };

  const getQuery = async (queryParams: PaginationQueryParameters) => {
    if (!talentProfileId) {
      return [];
    }

    const query = await getCampaignSDK().getCampaigns({
      ...queryParams,
      direction: PaginationDirection[queryParams.direction],
      searchTerm,
    });

    const withAnalytics = query.map(async (campaign) => {
      if (campaign.type !== CampaignType.SMART_SCHEDULE_EMAIL)
        return {
          ...campaign,
          openRate: 0,
          clickRate: 0,
        };

      const stats = await safeFetchStats(campaign.id);
      return { ...campaign, ...stats };
    });

    return Promise.all(withAnalytics);
  };

  const countQuery = async (countParams: CountQueryParameters) => {
    if (!talentProfileId) {
      return 0;
    }

    return (
      (await getCampaignSDK().getCampaignsCount({ ...countParams, searchTerm })) ?? 0
    );
  };

  return useOffsetPagination("campaigns", getQuery, countQuery, 10, "DESC", [
    talentProfileId,
    searchTerm,
  ]);
}

export function useIsPhoneNumberSetupPending() {
  const { isLoading, data } = useQuery({
    queryKey: ["phoneNumberService-getAssignedNumbers"],
    queryFn: () => getPhoneNumberService().getAssignedNumbers(),
  });

  return !isLoading && data?.length === 0;
}
