import ky from 'ky'

function getBackendProdUrl() {
  const getWebappBackendUrlFn =
    (window as any)['getWebAppBackendUrl'] || (parent as any)['getWebAppBackendUrl']
  if (typeof getWebappBackendUrlFn === 'function') {
    return getWebappBackendUrlFn('')
  }
  return null
}

const backendProdBase = getBackendProdUrl()
// @ts-expect-error - import.meta is not defined in the browser
let baseURLVite = import.meta.env.BASE_URL
// @ts-expect-error - import.meta is not defined in the browser
const localBackendPort = import.meta.env.VITE_API_PORT
// @ts-expect-error - import.meta is not defined in the browser
const localClientPort = import.meta.env.VITE_CLIENT_PORT

baseURLVite = baseURLVite.replace(localClientPort, localBackendPort)

const baseURL = backendProdBase != null ? backendProdBase : baseURLVite
const kyClient = ky.create({ prefixUrl: `${baseURL}api` })

export default kyClient
