initializeApiKey method

Future<ApiKeyValidationResult> initializeApiKey({
  1. required String apiKey,
  2. String environment = 'production',
  3. bool enableLogging = false,
  4. int timeout = 30000,
  5. int retryAttempts = 3,
  6. String? baseUrl,
  7. bool offlineMode = false,
})

Initialize API key with validation according to backend specification

Implementation

Future<ApiKeyValidationResult> initializeApiKey({
  required String apiKey,
  String environment = 'production',
  bool enableLogging = false,
  int timeout = 30000,
  int retryAttempts = 3,
  String? baseUrl,
  bool offlineMode = false,
}) async {
  try {
    if (enableLogging) {
      OnairosDebugHelper.log('🔑 Initializing API Key with validation');
      OnairosDebugHelper.log('   Environment: $environment');
      OnairosDebugHelper.log('   Offline Mode: $offlineMode');
    }

    // Check admin keys first (internal use)
    if (_isAdminKey(apiKey)) {
      if (enableLogging) {
        OnairosDebugHelper.log('✅ Using admin key - skipping validation');
      }
      return ApiKeyValidationResult(
        isValid: true,
        permissions: ['*'],
        rateLimits: RateLimits(
          remaining: 999999,
          resetTime: DateTime.now().add(Duration(days: 1)).millisecondsSinceEpoch,
        ),
        keyType: 'admin',
      );
    }

    // Validate API key format according to spec
    final keyType = _getApiKeyType(apiKey);
    if (keyType == 'invalid') {
      if (enableLogging) {
        OnairosDebugHelper.log('❌ Invalid API key format');
      }
      return ApiKeyValidationResult(
        isValid: false,
        keyType: 'invalid',
        error: 'Invalid API key format',
        message: 'Developer keys must be at least 32 characters and start with \'dev_\', \'pk_\', or \'ona_\'',
        code: 'INVALID_API_KEY_FORMAT',
      );
    }

    // If offline mode is enabled, skip API validation
    // This is useful when the backend is unavailable or for testing
    if (offlineMode) {
      if (enableLogging) {
        OnairosDebugHelper.log('⚠️  Offline mode enabled - skipping API validation');
        OnairosDebugHelper.log('   Using client-side validation only');
      }
      return ApiKeyValidationResult(
        isValid: true,
        permissions: ['read', 'write'],
        rateLimits: RateLimits(
          remaining: 1000,
          resetTime: DateTime.now().add(Duration(hours: 1)).millisecondsSinceEpoch,
        ),
        keyType: keyType,
        message: 'Offline mode - API key format validated locally',
      );
    }

    // Make API validation call with retry logic
    final result = await _validateApiKeyWithRetry(
      apiKey: apiKey,
      environment: environment,
      timeout: timeout,
      retryAttempts: retryAttempts,
      baseUrl: baseUrl,
      enableLogging: enableLogging,
    );

    // If backend is unavailable (502, 503, etc.), fall back to offline mode
    if (!result.isValid && _isBackendUnavailable(result)) {
      if (enableLogging) {
        OnairosDebugHelper.log('⚠️  Backend unavailable - falling back to offline mode');
        OnairosDebugHelper.log('   API key format is valid, continuing with limited validation');
      }
      return ApiKeyValidationResult(
        isValid: true,
        permissions: ['read', 'write'],
        rateLimits: RateLimits(
          remaining: 1000,
          resetTime: DateTime.now().add(Duration(hours: 1)).millisecondsSinceEpoch,
        ),
        keyType: keyType,
        message: 'Backend unavailable - using offline mode',
        code: 'OFFLINE_MODE_FALLBACK',
      );
    }

    return result;

  } catch (e) {
    if (enableLogging) {
      OnairosDebugHelper.log('❌ Error initializing API key: $e');
    }
    return ApiKeyValidationResult(
      isValid: false,
      keyType: 'invalid',
      error: 'SDK initialization failed',
      message: e.toString(),
      code: 'INITIALIZATION_ERROR',
    );
  }
}