import ky from 'ky'

interface WindowWithBackendUrl extends Window {
  getWebAppBackendUrl?: (arg: string) => string
}

const globalWindow = window as WindowWithBackendUrl
const globalParent = window.parent as WindowWithBackendUrl

export function getBackendUrl(): string {
  const getWebappBackendUrlFn = globalWindow.getWebAppBackendUrl || globalParent.getWebAppBackendUrl
  let backendUrl: string | null = null

  if (typeof getWebappBackendUrlFn === 'function') {
    backendUrl = getWebappBackendUrlFn('')
  }

  return backendUrl ?? 'http://localhost:5000'
}

export const api = ky.create({
  prefixUrl: getBackendUrl(),
  timeout: 10000,
})
