function normalizeApiBase(value?: string) {
  const base = (value || '').trim().replace(/\/+$/, '')
  if (!base) return ''
  return /\/api$/i.test(base) ? base : `${base}/api`
}

function isAbsoluteApiBase(value?: string) {
  return /^https?:\/\//i.test(value || '')
}

export const serverApiBase = normalizeApiBase(
  process.env.API_INTERNAL_URL
  || process.env.SERVER_API_BASE_URL
  || process.env.WEB_INTERNAL_API_BASE_URL
  || (isAbsoluteApiBase(process.env.NEXT_PUBLIC_API_BASE_URL) ? process.env.NEXT_PUBLIC_API_BASE_URL : '')
  || (process.env.NODE_ENV === 'production' ? 'http://backend:4000/api' : 'http://localhost:4000/api'),
)

const publicApiBase = normalizeApiBase(process.env.NEXT_PUBLIC_API_BASE_URL) || '/api'
const publicApiOrigin = publicApiBase.replace(/\/api\/?$/, '')

export function publicAssetUrl(value?: string | null) {
  if (!value) return ''
  if (/^(https?:|data:|blob:)/.test(value)) return value
  if (value.startsWith('/')) return `${publicApiOrigin}${value}`
  return value
}

export async function serverFetchJson<T>(path: string): Promise<T | null> {
  try {
    const response = await fetch(`${serverApiBase}${path}`, { cache: 'no-store' })
    if (!response.ok) return null
    return await response.json() as T
  } catch (error) {
    console.error('server_api_fetch_failed', { path, error })
    return null
  }
}
