import * as plugins from '../plugins.js';

export function normalizeHostname(valueArg: string): string {
  const trimmedValue = valueArg.trim().toLowerCase();
  if (!trimmedValue) return '';

  const withoutProtocol = trimmedValue.replace(/^[a-z][a-z0-9+.-]*:\/\//, '');
  const withoutPath = withoutProtocol.split('/')[0].split('?')[0].split('#')[0];
  return withoutPath.replace(/:\d+$/, '').replace(/\.$/, '');
}

export function normalizePasskeyHostname(valueArg: string): string | null {
  const candidate = valueArg.trim().toLowerCase();
  const normalized = normalizeHostname(candidate);
  if (
    !candidate
    || candidate !== normalized
    || !isValidHostname(normalized)
    || plugins.nodeNet.isIP(normalized) !== 0
  ) {
    return null;
  }
  return normalized;
}

export function isValidHostname(hostnameArg: string): boolean {
  if (!hostnameArg) return true;
  if (hostnameArg.length > 253) return false;
  return hostnameArg.split('.').every((label) => {
    if (!label || label.length > 63) return false;
    return /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label);
  });
}
