/**
 * Returns a safe internal redirect path, or the provided fallback.
 *
 * Only same-origin relative paths are allowed (must start with a single "/" and not
 * "//", which the browser treats as protocol-relative -> external). This prevents
 * open-redirect attacks via a `?redirect=` parameter.
 */
export function safeInternalPath(value: string | null | undefined, fallback: string = '/'): string {
  if (!value) return fallback;
  // Must be a relative path rooted at "/", but not "//" or "/\" (protocol-relative).
  if (!value.startsWith('/')) return fallback;
  if (value.startsWith('//') || value.startsWith('/\\')) return fallback;
  // Reject attempts to smuggle a scheme or control characters.
  if (/[\x00-\x1f]/.test(value) || value.includes('\\')) return fallback;
  return value;
}

/**
 * Returns true if a URL is safe to use as an external navigation target:
 * an absolute https:// URL, or a same-origin relative path.
 */
export function isSafeExternalUrl(value: string | null | undefined): boolean {
  if (!value) return false;
  if (value.startsWith('/') && !value.startsWith('//') && !value.startsWith('/\\')) return true;
  try {
    const url = new URL(value);
    return url.protocol === 'https:';
  } catch {
    return false;
  }
}
