import { isLocal } from './utils'

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('')
  }

  let baseURLVite = import.meta.env.BASE_URL
  const localBackendPort = import.meta.env.VITE_API_PORT
  const localClientPort = import.meta.env.VITE_CLIENT_PORT

  if (localClientPort && localBackendPort) {
    baseURLVite = baseURLVite.replace(localClientPort, localBackendPort)
  }

  return backendUrl ?? baseURLVite
}

export function getSocketConfig(): { host: string; path: string } {
  if (isLocal()) {
    const apiPort = import.meta.env.VITE_API_PORT
    return { host: `http://127.0.0.1:${apiPort}`, path: '/stream' }
  }

  /* DSS iframe (or other reverse-proxy) case ---------------------- */
  const base = getBackendUrl().replace(/\/$/, '') // strip trailing /
  return { host: '/', path: `${base}/stream` }
}
