import { useQuery } from "@tanstack/react-query";
import { selectTalentProfile } from "redux/User/selector";
import { useTypedSelector } from "redux/rootReducer";
import { getCampaignSDK, messagingAdaptor } from "services";
import notification from "utils/notification";

// structured like this due to legacy campaign adapter
export const useCampaignQuery = (campaignId: string) => {
  const talentProfile = useTypedSelector(selectTalentProfile);
  return useQuery({
    queryKey: ["campaigns", campaignId],
    queryFn: async () => {
      const res = await messagingAdaptor.getCampaign(
        talentProfile?.id!,
        campaignId
      );

      if (!res)
        return void notification.error({ message: "Something went wrong" });
      if (!("ok" in res))
        return void notification.error({ message: res.message });

      return res.response.campaign;
    },
    enabled: Boolean(talentProfile?.id) && Boolean(campaignId),
  });
};

export const useCampaignClickStatsQuery = (
  campaignId: string | undefined | null
) => {
  return useQuery({
    queryKey: ["campaigns", campaignId, "click-stats"],
    queryFn: async () =>
      await getCampaignSDK().email.getCampaignClickStats(campaignId!, {
        includeTemplateText: true,
      }),
    enabled: Boolean(campaignId),
  });
};

export const useCampaignAnalyticsQuery = (
  campaignId: string | undefined | null
) => {
  return useQuery({
    queryKey: ["campaigns", campaignId, "agg-stats"],
    queryFn: async () =>
      await getCampaignSDK().email.getCampaignAnalytics(campaignId!),
    enabled: Boolean(campaignId),
  });
};
