import Constants from 'expo-constants'
import { Platform } from 'react-native'

function stripTrailingSlash(url: string): string {
  return url.replace(/\/+$/, '')
}

function extractHost(hostUri?: string | null): string | null {
  if (!hostUri) return null
  const [host] = hostUri.split(':')
  return host || null
}

function resolveExpoHost(): string | null {
  const fromExpoConfig = (Constants.expoConfig as any)?.hostUri as string | undefined
  const fromManifest2 = (Constants as any)?.manifest2?.extra?.expoClient?.hostUri as
    | string
    | undefined
  const fromManifest = (Constants as any)?.manifest?.debuggerHost as string | undefined

  return extractHost(fromExpoConfig ?? fromManifest2 ?? fromManifest ?? null)
}

export function getApiBaseUrl(): string {
  const configuredApiUrl =
    process.env.EXPO_PUBLIC_API_URL ??
    ((Constants.expoConfig?.extra as { apiUrl?: string } | undefined)?.apiUrl ?? undefined)

  if (configuredApiUrl && !configuredApiUrl.includes('localhost')) {
    return stripTrailingSlash(configuredApiUrl)
  }

  const expoHost = resolveExpoHost()
  if (expoHost) {
    return `http://${expoHost}:3000`
  }

  if (configuredApiUrl) {
    return stripTrailingSlash(configuredApiUrl)
  }

  const fallbackHost = Platform.OS === 'android' ? '10.0.2.2' : '127.0.0.1'
  return `http://${fallbackHost}:3000`
}
