const { normalizeUrl } = require('./config')

/**
 * Normalize configured `cmsUrl` into the HTTP origin (scheme + host [+ port]) that should be used
 * when constructing absolute URLs for CMS HTTP APIs.
 *
 * Users sometimes set `cmsUrl` to `https://host/api` because the CMS serves APIs under `/api/*`.
 * The CLI already prefixes routes with `/api/...` (see `src/lib/api.js`), so keeping `/api` in
 * `cmsUrl` produces `/api/api/...` URLs for ad-hoc requests (notably media upload), which can
 * surface as confusing 404s like `POST:/media/upload` depending on server routing/proxies.
 *
 * @param {string} rawCmsUrl
 * @returns {string}
 */
function resolveCmsHttpBaseUrl(rawCmsUrl) {
  const trimmed = normalizeUrl(String(rawCmsUrl || '').trim())
  if (!trimmed) return trimmed

  let u
  try {
    u = new URL(trimmed)
  } catch {
    return trimmed
  }

  // Strip a trailing `/api` path segment if present (with or without trailing slash already removed)
  if (u.pathname === '/api' || u.pathname.endsWith('/api')) {
    return `${u.origin}`
  }

  // Default: keep configured origin + pathname (rare), but never guess beyond trimming `/api`.
  return `${u.origin}${u.pathname === '/' ? '' : u.pathname}`
}

module.exports = {
  resolveCmsHttpBaseUrl,
}
