/**
 * Unified URL Resolver
 * Single source of truth for resolving service URLs across all systems
 * (probes, health checks, health checker auto-config, SSO).
 */

/**
 * Resolve the canonical URL for a service.
 *
 * Priority:
 *   1. internet → https://www.google.com
 *   2. isExternal + externalUrl → use as-is
 *   3. service.url → prepend https:// if no protocol
 *   4. dnsServers config → http://{ip}:{port}
 *   5. fallback → buildServiceUrl(id)
 *
 * @param {string} id - service identifier
 * @param {Object|null} service - service object from services.json (may be null for top-card services)
 * @param {Object|null} siteConfig - site config containing dnsServers etc.
 * @param {Function} buildServiceUrl - fallback URL builder (subdomain or subdirectory mode)
 * @returns {string} resolved URL
 */
function resolveServiceUrl(id, service, siteConfig, buildServiceUrl) {
  if (id === 'internet') return 'https://www.google.com';
  if (service?.isExternal && service.externalUrl) return service.externalUrl;
  if (service?.url) return service.url.startsWith('http') ? service.url : `https://${service.url}`;
  const dnsServer = siteConfig?.dnsServers?.[id];
  if (dnsServer) return `http://${dnsServer.ip}:${dnsServer.port || 5380}`;
  return buildServiceUrl(id);
}

module.exports = { resolveServiceUrl };
