import { getRuntimeAdminBaseUrl, normalizeAdminBaseUrl } from '@/lib/runtime-config'

const envFrontendBaseUrl = normalizeAdminBaseUrl(import.meta.env.VITE_FRONTEND_BASE_URL)
const DEV_FRONTEND_BASE_URL = 'http://localhost:4321'
const PROD_DEFAULT_FRONTEND_PORT = '4321'

export function getFrontendBaseUrl() {
  const runtimeFrontendBaseUrl = getRuntimeAdminBaseUrl('frontendBaseUrl')
  if (runtimeFrontendBaseUrl) {
    return runtimeFrontendBaseUrl
  }

  if (envFrontendBaseUrl) {
    return envFrontendBaseUrl
  }

  if (import.meta.env.DEV || typeof window === 'undefined') {
    return DEV_FRONTEND_BASE_URL
  }

  const { protocol, hostname } = window.location
  return `${protocol}//${hostname}:${PROD_DEFAULT_FRONTEND_PORT}`
}

export function buildFrontendUrl(path = '/') {
  const normalizedPath = path.startsWith('/') ? path : `/${path}`
  return `${getFrontendBaseUrl()}${normalizedPath}`
}
