// ignore_for_file: avoid_web_libraries_in_flutter

import 'dart:js_interop';
import 'auth_token_store_backend.dart';

@JS('window.localStorage')
external _JSStorage get _localStorage;

@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 AuthTokenStore extends AuthTokenStoreBackend {
  AuthTokenStore()
    : super(
        localTarget: _JsStorageTarget(_localStorage),
        sessionTarget: _JsStorageTarget(_sessionStorage),
      );
}

class _JsStorageTarget implements AuthTokenStorageTarget {
  _JsStorageTarget(this._storage);

  final _JSStorage _storage;

  @override
  String? read(String key) {
    return _storage.getItem(key);
  }

  @override
  void remove(String key) {
    _storage.removeItem(key);
  }

  @override
  void write(String key, String value) {
    _storage.setItem(key, value);
  }
}

final authTokenStore = AuthTokenStore();
