const RECOMMENDATION_LINK_LABEL = {
  CVE: "View CVE",
  HUB: "View in Prowler Hub",
  ADVISORY: "View Advisory",
  REFERENCE: "View Reference",
} as const;

export type RecommendationLinkLabel =
  (typeof RECOMMENDATION_LINK_LABEL)[keyof typeof RECOMMENDATION_LINK_LABEL];

const CVE_HOSTS = new Set(["www.cve.org", "cve.org", "cve.mitre.org"]);

interface RecommendationLinkRule {
  label: RecommendationLinkLabel;
  matches: (url: URL) => boolean;
}

const RECOMMENDATION_LINK_RULES: RecommendationLinkRule[] = [
  {
    label: RECOMMENDATION_LINK_LABEL.CVE,
    matches: (url) => CVE_HOSTS.has(url.hostname.toLowerCase()),
  },
  {
    label: RECOMMENDATION_LINK_LABEL.HUB,
    matches: (url) => url.hostname.toLowerCase() === "hub.prowler.com",
  },
  {
    label: RECOMMENDATION_LINK_LABEL.ADVISORY,
    matches: (url) =>
      url.hostname.toLowerCase() === "github.com" &&
      url.pathname.startsWith("/advisories/"),
  },
];

function safeParseUrl(url: string): URL | null {
  try {
    return new URL(url);
  } catch {
    return null;
  }
}

export function getRecommendationLinkLabel(
  url: string,
): RecommendationLinkLabel {
  const parsedUrl = safeParseUrl(url);

  if (!parsedUrl) {
    return RECOMMENDATION_LINK_LABEL.REFERENCE;
  }

  return (
    RECOMMENDATION_LINK_RULES.find((rule) => rule.matches(parsedUrl))?.label ??
    RECOMMENDATION_LINK_LABEL.REFERENCE
  );
}
