// Environment configuration for React frontend
export type Environment = 'development' | 'staging' | 'production';

export interface AppConfig {
  environment: Environment;
  apiUrl: string;
  debug: boolean;
  logLevel: string;
}

// Get environment from process.env
export const getEnvironment = (): Environment => {
  const env = process.env.REACT_APP_ENVIRONMENT as Environment;
  
  // Fallback to NODE_ENV if REACT_APP_ENVIRONMENT is not set
  if (!env) {
    const nodeEnv = process.env.NODE_ENV;
    switch (nodeEnv) {
      case 'production':
        return 'production';
      case 'development':
        return 'development';
      default:
        return 'development';
    }
  }
  
  return env;
};

// Get API URL based on environment
export const getApiUrl = (): string => {
  const apiUrl = process.env.REACT_APP_API_URL;
  
  if (apiUrl) {
    return apiUrl;
  }
  
  // Fallback based on environment
  const env = getEnvironment();
  switch (env) {
    case 'production':
      return '/api/v1'; // Relative URL for production
    case 'staging':
      return 'https://staging-api.yourdomain.com/api/v1';
    case 'development':
    default:
      return 'http://localhost:8080/api/v1';
  }
};

// Get debug flag
export const isDebugMode = (): boolean => {
  const debug = process.env.REACT_APP_DEBUG;
  if (debug !== undefined) {
    return debug === 'true';
  }
  
  // Fallback based on environment
  return getEnvironment() === 'development';
};

// Get log level
export const getLogLevel = (): string => {
  return process.env.REACT_APP_LOG_LEVEL || 'info';
};

// Get complete app configuration
export const getAppConfig = (): AppConfig => {
  return {
    environment: getEnvironment(),
    apiUrl: getApiUrl(),
    debug: isDebugMode(),
    logLevel: getLogLevel(),
  };
};

// Environment checks
export const isDevelopment = (): boolean => {
  return getEnvironment() === 'development';
};

export const isStaging = (): boolean => {
  return getEnvironment() === 'staging';
};

export const isProduction = (): boolean => {
  return getEnvironment() === 'production';
};

// Log configuration (only in development)
export const logConfig = (): void => {
  if (isDevelopment()) {
    const config = getAppConfig();
    console.log('🚀 Frontend Configuration:', {
      environment: config.environment,
      apiUrl: config.apiUrl,
      debug: config.debug,
      logLevel: config.logLevel,
    });
  }
};
