initialize method

Future<void> initialize({
  1. String? apiKey,
  2. String? environment,
  3. bool autoInitWithAdmin = true,
  4. bool enableLogging = false,
  5. int timeout = 30000,
  6. int retryAttempts = 3,
  7. bool offlineMode = false,
})

Initialize the API key service with proper validation

Implementation

Future<void> initialize({
  String? apiKey,
  String? environment,
  bool autoInitWithAdmin = true,
  bool enableLogging = false,
  int timeout = 30000,
  int retryAttempts = 3,
  bool offlineMode = false,
}) async {
  try {
    if (enableLogging) {
      OnairosDebugHelper.log('🔑 Initializing API Key Service with validation');
    }

    // If no API key provided and auto-init is enabled, use admin key
    if (apiKey == null && autoInitWithAdmin) {
      apiKey = ADMIN_API_KEY;
      if (enableLogging) {
        OnairosDebugHelper.log('⚠️  Using admin API key for development - apps should provide their own key');
      }
    }

    // Validate API key using the new validation service
    if (apiKey != null) {
      final validationService = ApiKeyValidationService();
      final validationResult = await validationService.initializeApiKey(
        apiKey: apiKey,
        environment: environment ?? 'production',
        enableLogging: enableLogging,
        timeout: timeout,
        retryAttempts: retryAttempts,
        offlineMode: offlineMode,
      );

      if (!validationResult.isValid) {
        final errorMsg = validationResult.error ?? 'Unknown error';
        final errorCode = validationResult.code ?? 'UNKNOWN';
        throw Exception('API key validation failed: $errorMsg (Code: $errorCode)');
      }

      if (enableLogging) {
        OnairosDebugHelper.log('✅ API key validated successfully');
        if (validationResult.message != null) {
          OnairosDebugHelper.log('   ${validationResult.message}');
        }
        if (validationResult.permissions != null) {
          OnairosDebugHelper.log('📋 Permissions: ${validationResult.permissions}');
        }
      }
    }

    // Store configuration
    _currentApiKey = apiKey;
    _environment = environment ?? 'production';

    if (apiKey != null) {
      await _storage.write(key: 'onairos_api_key', value: apiKey);
    }
    await _storage.write(key: 'onairos_environment', value: _environment!);

    _isInitialized = true;
    if (enableLogging) {
      OnairosDebugHelper.log('✅ API Key Service initialized successfully');
    }

  } catch (e) {
    OnairosDebugHelper.log('❌ Error initializing API Key Service: $e');
    rethrow;
  }
}