// ignore_for_file: avoid_web_libraries_in_flutter

import 'dart:js_interop';
import 'login_challenge_loop_guard_base.dart';

@JS('window.sessionStorage')
external _JSStorage get _sessionStorage;

@JS()
extension type _JSStorage(JSObject _) implements JSObject {
  external String? getItem(String key);
  external void setItem(String key, String value);
  external void removeItem(String key);
}

class _WebLoginChallengeLoopGuard implements LoginChallengeLoopGuard {
  static const String _keyPrefix = 'baron_oidc_auto_accept_last:';

  String _key(String challenge) => '$_keyPrefix$challenge';

  @override
  bool shouldAllowAutoAccept(String loginChallenge, {int cooldownMs = 15000}) {
    final challenge = loginChallenge.trim();
    if (challenge.isEmpty) {
      return false;
    }
    try {
      final raw = _sessionStorage.getItem(_key(challenge));
      if (raw == null || raw.isEmpty) {
        return true;
      }
      final lastMs = int.tryParse(raw);
      if (lastMs == null) {
        return true;
      }
      final nowMs = DateTime.now().millisecondsSinceEpoch;
      return nowMs - lastMs > cooldownMs;
    } catch (_) {
      return true;
    }
  }

  @override
  void markAutoAcceptAttempt(String loginChallenge) {
    final challenge = loginChallenge.trim();
    if (challenge.isEmpty) {
      return;
    }
    try {
      final nowMs = DateTime.now().millisecondsSinceEpoch;
      _sessionStorage.setItem(_key(challenge), nowMs.toString());
    } catch (_) {}
  }

  @override
  void clear(String loginChallenge) {
    final challenge = loginChallenge.trim();
    if (challenge.isEmpty) {
      return;
    }
    try {
      _sessionStorage.removeItem(_key(challenge));
    } catch (_) {}
  }
}

LoginChallengeLoopGuard createLoginChallengeLoopGuard() {
  return _WebLoginChallengeLoopGuard();
}
