/**
 * Feature flags для системы SFERA
 *
 * Централизованное управление функциональностью и экспериментами.
 * Позволяет безопасно внедрять новые возможности с возможностью отката.
 */

export const FEATURE_FLAGS = {
  /**
   * Система безопасности данных в поставках
   * Контролирует фильтрацию коммерческих данных между участниками
   */
  SUPPLY_DATA_SECURITY: {
    enabled: process.env.ENABLE_SUPPLY_SECURITY === 'true',
    auditEnabled: process.env.ENABLE_SECURITY_AUDIT === 'true',
    strictMode: process.env.SECURITY_STRICT_MODE === 'true',
    cacheEnabled: process.env.SECURITY_CACHE_ENABLED !== 'false', // По умолчанию включено
    realTimeAlerts: process.env.SECURITY_REALTIME_ALERTS === 'true',
  },

  /**
   * Система партнерства и реферальных программ
   */
  PARTNERSHIP_SYSTEM: {
    enabled: process.env.ENABLE_PARTNERSHIPS !== 'false',
    autoPartnership: process.env.AUTO_PARTNERSHIP === 'true',
    referralBonuses: process.env.REFERRAL_BONUSES === 'true',
  },

  /**
   * Экспериментальные возможности
   */
  EXPERIMENTS: {
    newSupplyWorkflow: process.env.EXPERIMENT_NEW_SUPPLY_WORKFLOW === 'true',
    advancedAnalytics: process.env.EXPERIMENT_ADVANCED_ANALYTICS === 'true',
    aiRecommendations: process.env.EXPERIMENT_AI_RECOMMENDATIONS === 'true',
  },
} as const

/**
 * Проверка активности feature flag
 */
export function isFeatureEnabled(featurePath: string): boolean {
  const pathParts = featurePath.split('.')
  let current: unknown = FEATURE_FLAGS

  for (const part of pathParts) {
    if (typeof current !== 'object' || current === null || !(part in current)) {
      return false
    }
    current = (current as Record<string, unknown>)[part]
  }

  return Boolean(current)
}

/**
 * Получение всех активных feature flags
 */
export function getActiveFeatures(): Record<string, boolean> {
  const active: Record<string, boolean> = {}

  function traverse(obj: Record<string, unknown>, path = ''): void {
    for (const [key, value] of Object.entries(obj)) {
      const currentPath = path ? `${path}.${key}` : key

      if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
        traverse(value as Record<string, unknown>, currentPath)
      } else if (typeof value === 'boolean' && value === true) {
        active[currentPath] = true
      }
    }
  }

  traverse(FEATURE_FLAGS as Record<string, unknown>)
  return active
}

/**
 * Типы для TypeScript
 */
export type FeatureFlagPath =
  | 'SUPPLY_DATA_SECURITY.enabled'
  | 'SUPPLY_DATA_SECURITY.auditEnabled'
  | 'SUPPLY_DATA_SECURITY.strictMode'
  | 'SUPPLY_DATA_SECURITY.cacheEnabled'
  | 'SUPPLY_DATA_SECURITY.realTimeAlerts'
  | 'PARTNERSHIP_SYSTEM.enabled'
  | 'PARTNERSHIP_SYSTEM.autoPartnership'
  | 'PARTNERSHIP_SYSTEM.referralBonuses'
  | 'EXPERIMENTS.newSupplyWorkflow'
  | 'EXPERIMENTS.advancedAnalytics'
  | 'EXPERIMENTS.aiRecommendations'
