import axios from 'axios'

function normalizeApiBaseUrl(configuredBaseUrl) {
  if (!configuredBaseUrl) return '/api'

  if (/^https?:\/\//i.test(configuredBaseUrl)) {
    try {
      const url = new URL(configuredBaseUrl)
      if (
        process.env.NODE_ENV === 'production' &&
        (url.hostname === 'localhost' || url.hostname === '127.0.0.1')
      ) {
        return '/api'
      }
      return configuredBaseUrl
    } catch (e) {
      return '/api'
    }
  }

  return configuredBaseUrl
}

const baseURL = normalizeApiBaseUrl(process.env.VUE_APP_API_BASE_URL)

export const apiClient = axios.create({
  baseURL
})

export function buildPdfUrl(fileName) {
  if (!fileName) return ''
  const name = String(fileName)
  if (/^https?:\/\//i.test(name)) return name

  const encodedName = encodeURIComponent(name)
  const configuredBaseUrl = normalizeApiBaseUrl(process.env.VUE_APP_API_BASE_URL)
  if (configuredBaseUrl && /^https?:\/\//i.test(configuredBaseUrl)) {
    try {
      const url = new URL(configuredBaseUrl)
      return `${url.origin}/pdf/${encodedName}`
    } catch (e) {
      return `/pdf/${encodedName}`
    }
  }

  return `/pdf/${encodedName}`
}
