import { getCampaignSDK } from "../services";

import { useQuery } from "@tanstack/react-query";
import { ClickStat } from "@komi-app/creator-ui";

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

export const useEmailCampaignClickStats = (
  campaignId: string | null,
): { data: ClickStat[]; isLoading: boolean; isError: boolean } => {
  const query = useEmailCampaignClickStatsQuery(campaignId);
  if (!query.data || query.isLoading) {
    return { data: [], isLoading: true, isError: query.isError };
  }

  const clicks = query.data.clicks || [];

  // Map `EmailClickStatsAggCampaign` to `ClickStat`
  const data = clicks.map(({ url, uniqueClicks, totalClicks }) => ({
    name: url,
    unique: uniqueClicks,
    total: totalClicks,
  }));

  return { data, isLoading: false, isError: query.isError };
};
