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

const normalizeBaseUrl = (value: string): string => value.replace(/\/+$/, '');

const hostFromExpo = (): string | null => {
  const hostUri =
    Constants.expoConfig?.hostUri ??
    (Constants as unknown as { manifest2?: { extra?: { expoClient?: { hostUri?: string } } } }).manifest2?.extra
      ?.expoClient?.hostUri;

  if (!hostUri) return null;
  const host = hostUri.split(':')[0]?.trim();
  return host || null;
};

const detectDefaultBaseUrl = (): string => {
  const host = hostFromExpo();
  if (host && host !== 'localhost') {
    return `http://${host}:3000`;
  }

  if (Platform.OS === 'android') {
    return 'http://10.0.2.2:3000';
  }

  return 'http://localhost:3000';
};

export const API_BASE_URL = normalizeBaseUrl(process.env.EXPO_PUBLIC_API_BASE_URL || detectDefaultBaseUrl());
