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

const cleanUrl = (raw?: string | null): string => {
  if (!raw) return '';
  const sanitized = String(raw).replace(/\s+/g, '').replace(/\/+$/, '');
  if (!sanitized) return '';
  return sanitized.endsWith('/api') ? sanitized : `${sanitized}/api`;
};

const resolveApiBaseUrl = (): string => {
  // 1. Primary: explicitly defined in .env
  const fromEnv = cleanUrl(process.env.EXPO_PUBLIC_API_URL) || cleanUrl(process.env.EXPO_PUBLIC_APIURL);
  if (fromEnv) {
    return fromEnv;
  }

  // 2. Secondary: app.config.js / app.json extra
  const fromExtra = cleanUrl(Constants.expoConfig?.extra?.apiUrl);
  if (fromExtra) {
    return fromExtra;
  }

  // 3. Fallbacks when no .env is present
  if (Platform.OS === 'android') {
    return 'http://10.0.2.2:8000/api';
  }
  return 'http://127.0.0.1:8000/api';
};

export const AppConfig = {
  appName: 'TravelCam',
  version: '1.0.0',
  appEnv: process.env.EXPO_PUBLIC_APP_ENV || 'development',

  /**
   * The single source of truth for the API base URL across the mobile app.
   * Defined by EXPO_PUBLIC_API_URL in mobile/.env
   */
  get apiBaseUrl(): string {
    return resolveApiBaseUrl();
  },

  /**
   * Host IP address resolved from .env EXPO_PUBLIC_DEV_IP or parsed from apiBaseUrl.
   */
  get devIp(): string {
    if (process.env.EXPO_PUBLIC_DEV_IP) {
      return process.env.EXPO_PUBLIC_DEV_IP.replace(/\s+/g, '');
    }
    const match = this.apiBaseUrl.match(/https?:\/\/([^:/]+)/);
    return match ? match[1] : '127.0.0.1';
  },

  supportEmail: 'support@travelcam.cm',
  defaultLanguage: 'en',
  supportedLanguages: ['en', 'fr'],
};
