import 'dart:async';

/// Ensures only one token refresh runs at a time.
/// When multiple requests hit 401 simultaneously, only the first triggers
/// a refresh; the rest wait for the same result.
class TokenRefreshLock {
  Completer<bool>? _refreshCompleter;

  /// Returns true if refresh succeeded. If a refresh is already in progress,
  /// waits for that one instead of starting a new one.
  Future<bool> run(Future<bool> Function() refreshFn) async {
    // If a refresh is already running, wait for it
    if (_refreshCompleter != null) {
      return _refreshCompleter!.future;
    }

    _refreshCompleter = Completer<bool>();
    try {
      final result = await refreshFn();
      _refreshCompleter!.complete(result);
      return result;
    } catch (e) {
      _refreshCompleter!.complete(false);
      return false;
    } finally {
      _refreshCompleter = null;
    }
  }
}
