connectGmail method

Future<bool> connectGmail(
  1. BuildContext context
)

Connect to Gmail with proper OAuth configuration

Implementation

Future<bool> connectGmail(BuildContext context) async {
  try {
    // Get username from secure storage
    final username = await getFromSecure('username') ?? '';

    // Prepare request data with proper Gmail scope
    final Map<String, dynamic> requestData = {
      'session': {
        'username': username,
        'platform': 'gmail',
        'scope': 'https://www.googleapis.com/auth/gmail.readonly',
      }
    };

    // Request authorization URL from Onairos API
    final baseUrlGmail = await apiBaseUrl;
    final apiService = onairosapi(baseUrl: baseUrlGmail);
    final response = await apiService.post(
      'gmail/authorize',
      jsonData: jsonEncode(requestData),
    );

    if (response == null) {
      throw Exception('Failed to get Gmail authorization URL');
    }

    // Extract the authorization URL
    final String authUrl = response['gmailURL'] ?? response['authUrl'] ?? '';
    if (authUrl.isEmpty) {
      throw Exception('Invalid Gmail authorization URL');
    }

    // Show the OAuth WebView with special Gmail configuration
    final result = await showModalBottomSheet<bool>(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => OAuthWebViewScreen(
        platform: 'gmail',
        authUrl: authUrl,
        callbackUrlPattern: 'https://api2.onairos.uk/gmail/callback',
        isGmail: true, // Special flag for Gmail handling
      ),
    );

    return result ?? false;
  } catch (e) {
    print('Error in Gmail OAuth flow: $e');
    return false;
  }
}