/**
 * Environment configuration
 * Centralized environment variable management with type safety.
 * (Ported verbatim from fe0/src/shared/config/env.ts.)
 */

interface EnvConfig {
  API_URL: string;
  WS_URL?: string;
  ENVIRONMENT: 'development' | 'staging' | 'production';
  ENABLE_DEV_TOOLS: boolean;
  APP_NAME: string;
  APP_VERSION: string;
}

const getEnvVar = (key: string, defaultValue?: string): string => {
  const value = import.meta.env[key];
  if (!value && defaultValue === undefined) {
    if (import.meta.env.DEV) {
      console.warn(`Missing environment variable: ${key}. Using default: undefined`);
    }
  }
  return value || defaultValue || '';
};

const getBooleanEnvVar = (key: string, defaultValue = false): boolean => {
  const value = getEnvVar(key, String(defaultValue));
  return value === 'true' || value === '1';
};

/**
 * Base URL for API calls. In dev, default is "" (same origin) so requests hit `/api/...` and the
 * Vite dev proxy forwards to the backend — avoids CORS and fixes Docker (browser → :PORT, proxy → be0:4402).
 * Set `VITE_API_URL` explicitly (e.g. `http://localhost:4402`) if you want the browser to call the API host directly.
 */
function resolveApiUrl(): string {
  const raw = import.meta.env.VITE_API_URL as string | undefined;
  if (raw != null && String(raw).trim() !== '') {
    return String(raw).replace(/\/$/, '');
  }
  // Same-origin: Vite dev proxy (development) or nginx → be0 (production).
  return '';
}

export const env: EnvConfig = {
  API_URL: resolveApiUrl(),
  WS_URL: getEnvVar('VITE_WS_URL', ''),
  ENVIRONMENT: getEnvVar('VITE_ENV', 'development') as EnvConfig['ENVIRONMENT'],
  ENABLE_DEV_TOOLS: getBooleanEnvVar('VITE_ENABLE_DEV_TOOLS', false),
  APP_NAME: getEnvVar('VITE_APP_NAME', 'UMP Initiative'),
  APP_VERSION: getEnvVar('VITE_APP_VERSION', '1.0.0'),
};

export const isDevelopment = env.ENVIRONMENT === 'development';
export const isProduction = env.ENVIRONMENT === 'production';
export const isStaging = env.ENVIRONMENT === 'staging';
