/**
 * URL validators for inbound user input.
 *
 * Today only `isSafeHttpUrl` is used (lesson_plans.meet_url /
 * lesson_plans.classroom_url), but the helper is shared and small enough
 * to grow as new columns surface.
 *
 * Rules:
 *   - Empty / null / undefined → valid (means "no link set").
 *   - Strings must parse via WHATWG URL and use http(s) protocol only.
 *   - Non-string values (numbers, objects, etc.) → invalid.
 *
 * The check is intentionally permissive on host (no IP / DNS blocking).
 * The server only stores the URL and renders it as a link; clicking
 * happens client-side.
 */

/**
 * @param {unknown} value
 * @returns {boolean}
 */
function isSafeHttpUrl(value) {
  if (value === null || value === undefined) return true;
  if (typeof value !== 'string') return false;
  if (value.length === 0) return true;
  let parsed;
  try {
    parsed = new URL(value);
  } catch (_e) {
    return false;
  }
  return parsed.protocol === 'http:' || parsed.protocol === 'https:';
}

/**
 * Trim a URL and run `isSafeHttpUrl`. Returns null when invalid so the
 * caller can persist `null` rather than the bad string.
 */
function normalizeHttpUrl(value) {
  if (value === null || value === undefined) return null;
  if (typeof value !== 'string') return null;
  const trimmed = value.trim();
  if (trimmed.length === 0) return null;
  if (!isSafeHttpUrl(trimmed)) return null;
  return trimmed;
}

module.exports = { isSafeHttpUrl, normalizeHttpUrl };
