import type { ServerHttpProtocol } from './variables';

function formatHostForUrl(host: string): string {
  if (host.startsWith('[') || !host.includes(':')) {
    return host;
  }

  return `[${host}]`;
}

function getDisplayHost(serverHost: string | undefined): string {
  if (!serverHost || serverHost === '0.0.0.0' || serverHost === '::') {
    return 'localhost';
  }

  return serverHost;
}

export function buildSignalServerPublicUrl(
  serverProtocol: ServerHttpProtocol,
  serverHost: string | undefined,
  serverPort: number
): string {
  const displayHost = formatHostForUrl(getDisplayHost(serverHost));

  return `${serverProtocol}://${displayHost}:${serverPort}`;
}

export function resolveSignalServerTag(configuredTag: string | undefined, publicUrl: string): string {
  const normalizedTag = configuredTag?.trim();

  return normalizedTag || publicUrl;
}
