import type { CheckLink, CheckResult, CheckStatus, EdmCheck } from "../types";
import { getAnchors, isHttps } from "../htmlUtils";

const REQUIRED_UTM = ["utm_source", "utm_medium"];
const RECOMMENDED_UTM = ["utm_campaign"];

// Outbound links that should carry tracking (own marketing domains + CTAs).
const TRACKED_DOMAINS = ["karmagroup.com", "karmaconcierge.club", "karmaresorts"];

export const googleAnalyticsCheck: EdmCheck = {
  id: "googleAnalytics",
  label: "Google Analytics",
  description: "Checks utm_source / utm_medium (+ utm_campaign) on outbound tracking links.",
  run: ({ doc }): CheckResult => {
    const tracked = getAnchors(doc).filter(
      (a) => isHttps(a.href) && TRACKED_DOMAINS.some((d) => a.href.includes(d)),
    );

    if (!tracked.length) {
      return {
        status: "warning",
        messages: ["No outbound Karma links found to check UTM tracking on."],
      };
    }

    const links: CheckLink[] = [];
    const messages: string[] = [];
    let status: CheckStatus = "pass";
    let missingCount = 0;

    for (const a of tracked) {
      const query = a.href.split("?")[1] ?? "";
      const params = new URLSearchParams(query);
      const present = REQUIRED_UTM.filter((k) => (params.get(k) ?? "").trim() !== "");
      const recommended = RECOMMENDED_UTM.filter((k) => (params.get(k) ?? "").trim() !== "");
      const missing = REQUIRED_UTM.filter((k) => !present.includes(k));

      const carried = [...present, ...recommended];
      links.push({
        label: carried.length ? carried.join(", ") : "no UTM params",
        href: a.href,
        present: missing.length === 0,
        isMergeTag: false,
      });
      if (missing.length) missingCount++;
    }

    if (missingCount) {
      status = "warning";
      messages.push(`${missingCount}/${tracked.length} outbound link(s) missing utm_source/utm_medium.`);
    } else {
      messages.push(`All ${tracked.length} outbound link(s) carry utm_source + utm_medium.`);
    }
    messages.push(`utm_campaign is recommended on campaign links.`);

    return { status, messages, links };
  },
};
