import { env } from '@/lib/env';

const LOCAL_HOST_PATTERNS = [
  /^localhost(:\d+)?$/i,
  /^127\.\d+\.\d+\.\d+(:\d+)?$/,
  /^0\.0\.0\.0(:\d+)?$/,
  /^192\.168\.\d+\.\d+(:\d+)?$/,
  /^10\.\d+\.\d+\.\d+(:\d+)?$/,
  /^172\.(1[6-9]|2\d|3[01])\.\d+\.\d+(:\d+)?$/,
];

/**
 * Strip the scheme+host from a branding URL when the host is localhost
 * or a private LAN address, leaving a path-only URL the browser can
 * resolve against whatever origin it loaded the page from.
 *
 * Without this, a logo uploaded while the app ran at http://localhost:3000
 * is forever pinned to that host - fine for the dev's Mac, broken from
 * a phone on the LAN or any device with a different DNS view.
 *
 * Public-internet URLs (CDN, S3) pass through unchanged.
 */
export function normalizeBrandingUrl(url: string | null | undefined): string | null {
  if (!url) return null;
  const trimmed = url.trim();
  if (!trimmed) return null;
  if (trimmed.startsWith('/')) return trimmed;
  try {
    const parsed = new URL(trimmed);
    const isLocal = LOCAL_HOST_PATTERNS.some((re) => re.test(parsed.host));
    if (!isLocal) return trimmed;
    return `${parsed.pathname}${parsed.search}${parsed.hash}`;
  } catch {
    return trimmed;
  }
}

/**
 * Email surfaces (rendered HTML inboxes) cannot resolve path-only URLs -
 * the recipient's mail client has no origin context. Use this when
 * emitting branding into an email shell to guarantee an absolute URL.
 *
 * Pass-through for URLs that are already absolute.
 */
export function absolutizeBrandingUrl(url: string | null | undefined): string | null {
  if (!url) return null;
  const trimmed = url.trim();
  if (!trimmed) return null;
  if (/^https?:\/\//i.test(trimmed)) return trimmed;
  const base = env.APP_URL.replace(/\/+$/, '');
  return `${base}${trimmed.startsWith('/') ? '' : '/'}${trimmed}`;
}
