import 'login_challenge_loop_guard_base.dart';

class _InMemoryLoginChallengeLoopGuard implements LoginChallengeLoopGuard {
  final Map<String, int> _lastAttemptAtMs = <String, int>{};

  @override
  bool shouldAllowAutoAccept(String loginChallenge, {int cooldownMs = 15000}) {
    final challenge = loginChallenge.trim();
    if (challenge.isEmpty) {
      return false;
    }
    final nowMs = DateTime.now().millisecondsSinceEpoch;
    final lastMs = _lastAttemptAtMs[challenge];
    if (lastMs == null) {
      return true;
    }
    return nowMs - lastMs > cooldownMs;
  }

  @override
  void markAutoAcceptAttempt(String loginChallenge) {
    final challenge = loginChallenge.trim();
    if (challenge.isEmpty) {
      return;
    }
    _lastAttemptAtMs[challenge] = DateTime.now().millisecondsSinceEpoch;
  }

  @override
  void clear(String loginChallenge) {
    _lastAttemptAtMs.remove(loginChallenge.trim());
  }
}

LoginChallengeLoopGuard createLoginChallengeLoopGuard() {
  return _InMemoryLoginChallengeLoopGuard();
}
