// Amazon Associates tracking IDs, keyed by Amazon hostname.
// Add additional marketplaces here when applicable (each marketplace issues its own ID).
const AMAZON_TAGS: Record<string, string> = {
  'amazon.com': 'unique.rzen.dev-20',
};

// Hostnames that always belong to the US marketplace (short links resolve there).
const AMAZON_US_SHORTLINKS = new Set(['amzn.to', 'a.co']);

function normalizeHost(host: string): string {
  return host.toLowerCase().replace(/^www\./, '');
}

function amazonHostFor(host: string): string | null {
  const h = normalizeHost(host);
  if (AMAZON_US_SHORTLINKS.has(h)) return 'amazon.com';
  if (h === 'smile.amazon.com') return 'amazon.com';
  if (h === 'amazon.com' || h.endsWith('.amazon.com')) return 'amazon.com';
  // Other regional marketplaces (amazon.co.uk, amazon.de, etc.). Only mark as
  // affiliate when we have a tag configured for that marketplace.
  const match = h.match(/^(?:[\w-]+\.)?(amazon\.(?:[a-z.]+))$/);
  return match ? match[1] : null;
}

export function isAmazonUrl(url: string): boolean {
  try {
    return amazonHostFor(new URL(url).hostname) !== null;
  } catch {
    return false;
  }
}

export interface ExternalLink {
  href: string;
  isAffiliate: boolean;
  network?: 'amazon';
}

/**
 * Returns the link to render externally. If the URL points at an Amazon
 * marketplace we have a tag for, append the tag and flag it as affiliate.
 * Otherwise return the URL unchanged.
 */
export function resolveExternalLink(rawUrl: string): ExternalLink {
  try {
    const u = new URL(rawUrl);
    const marketplace = amazonHostFor(u.hostname);
    if (!marketplace) return { href: rawUrl, isAffiliate: false };
    const tag = AMAZON_TAGS[marketplace];
    if (!tag) return { href: rawUrl, isAffiliate: false, network: 'amazon' };
    u.searchParams.set('tag', tag);
    return { href: u.toString(), isAffiliate: true, network: 'amazon' };
  } catch {
    return { href: rawUrl, isAffiliate: false };
  }
}

export const AFFILIATE_REL = 'sponsored noopener noreferrer';
export const AFFILIATE_DISCLOSURE =
  'Affiliate link — we may earn a commission from qualifying Amazon purchases at no extra cost to you.';
