/**
 * Validate an external URL string. Returns the URL only if it parses and uses
 * an http/https scheme — otherwise null.
 *
 * Defends against:
 *   - javascript: URLs (XSS via href clicks)
 *   - data: URLs (data exfiltration, weird content)
 *   - file:, ftp:, custom-scheme abuse
 *   - malformed strings (null reference protection)
 *
 * Closes finding #3 from 2026-05-24 trade-in audit. Backend supplies
 * lot.source_url verbatim from scraped sites — must not trust the string.
 */
export function safeUrl(raw: string | null | undefined): string | null {
  if (!raw || typeof raw !== "string") return null;
  try {
    const u = new URL(raw);
    if (u.protocol !== "http:" && u.protocol !== "https:") return null;
    return u.toString();
  } catch {
    return null;
  }
}
