start method

Future<void> start()

Implementation

Future<void> start() async {
  if (_isActive && !_isCancelled) {
    onSessionError?.call('Session already running.');
    return;
  }
  _isActive = true;

  final isConnected = InternetConnectionService.isConnected();
  if (!await isConnected) {
    onSessionError?.call('No internet connection.');
    _cancelInternal();
    return;
  }

  try {
    final deviceData = await _requestDeviceCode();
    if (deviceData == null) {
      onSessionError?.call('Failed to get device code.');
      return;
    }

    // Notify app to show user code + URI
    onAuthCodeReceived?.call(
      deviceData['user_code'],
      deviceData['verification_uri'],
    );

    // Start timeout timer
    _timeoutTimer = Timer(timeoutDuration, () {
      _cancelInternal();
      onSessionTimeout?.call();
    });

    // Start polling
    final token = await _pollForAccessToken(
      deviceData['device_code'],
      deviceData['interval'],
    );

    if (token != null) {
      _cleanup();
      onSessionCompleted?.call(token);
    } else if (!_isCancelled) {
      // If polling ended without cancel, treat as error
      onSessionError?.call('Failed to obtain access token.');
    }
  } on TimeoutException {
    _cancelInternal();
    onSessionError?.call('⏱️ Network timeout. Please check your connection.');
  } catch (e) {
    if (!_isCancelled) {
      _cancelInternal();
      onSessionError?.call('Exception: $e');
    }
  }
}