authenticate method

Future<AuthResult> authenticate({
  1. required String apiKey,
  2. required String deviceId,
  3. String? buildToken,
})

Authenticate with API key Returns auth response with tokens

Implementation

Future<AuthResult> authenticate({
  required String apiKey,
  required String deviceId,
  String? buildToken,
}) async {
  try {
    // Build authenticate request JSON via C++
    final requestJson = _buildAuthenticateRequestJSON(
      apiKey: apiKey,
      deviceId: deviceId,
      buildToken: buildToken,
    );

    if (requestJson == null) {
      return AuthResult.failure('Failed to build auth request');
    }

    // Make HTTP request
    final endpoint = _getAuthEndpoint();
    final baseURL = _baseURL ?? _getDefaultBaseURL();
    final url = Uri.parse('$baseURL$endpoint');

    _logger.debug('Auth POST to: $url');
    _logger.debug('Auth body: $requestJson');

    final response = await http.post(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
      body: requestJson,
    );

    _logger.debug('Auth response status: ${response.statusCode}');
    _logger.debug('Auth response body: ${response.body}');

    if (response.statusCode == 200 || response.statusCode == 201) {
      // Parse response and store tokens
      final authData = _parseAuthResponse(response.body);

      // Try C++ handler first
      final cppSuccess = _handleAuthenticateResponse(response.body);

      // Also manually store tokens in secure storage (in case C++ handler unavailable)
      await _storeAuthTokens(authData);

      if (cppSuccess || authData.accessToken != null) {
        _logger.info('Authentication successful');
        return AuthResult.success(authData);
      } else {
        return AuthResult.failure('Failed to parse auth response');
      }
    } else {
      // Parse API error
      final errorMsg = _parseAPIError(response.body, response.statusCode);
      return AuthResult.failure(errorMsg);
    }
  } catch (e) {
    _logger.error('Authentication error', metadata: {'error': e.toString()});
    return AuthResult.failure(e.toString());
  }
}