import { getDomain } from "tldts";

/**
 * The registered domain an app's health API lives on, e.g.
 * "https://api.calai.twilbp.com/health" → "twilbp.com" and
 * "https://x.example.co.in/" → "example.co.in" (public suffix list, not "last two labels").
 * Null for IP addresses, single-label hosts such as "localhost", and unparsable URLs:
 * there is no domain registration to watch.
 */
export function registeredDomain(url: string): string | null {
  let hostname: string;
  try {
    hostname = new URL(url).hostname; // already lower-case, punycode for IDNs
  } catch {
    return null;
  }
  return getDomain(hostname) ?? null;
}

/** "twilbp.com" → "com", "example.co.in" → "in": the ending whose registry holds the record. */
export function topLevelDomain(domain: string): string {
  return domain.slice(domain.lastIndexOf(".") + 1);
}

/**
 * What someone typed into "Add Domain" → the registered domain to watch.
 * Accepts "dualnum.com", "www.dualnum.com", "api.dualnum.com:8443" or a full URL;
 * subdomains are dropped because the registration (and its expiry) belongs to the
 * registered domain. Null when there is no registered domain in it (IP, "localhost", junk).
 */
export function domainFromInput(input: string): string | null {
  const trimmed = input.trim();
  if (trimmed === "" || /\s/.test(trimmed)) return null;
  return registeredDomain(/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`);
}
