import 'package:commons_core/commons_core.dart';

import '../security/secret_store.dart';

/// Persists the web-of-trust parameters (Duniter sigQty / stepMax / validity),
/// so a young network can loosen them and tighten as it grows — exactly how Ğ1
/// itself evolved. Defaults to [WotParams.duniter]. Keystore-backed.
class WotSettings {
  WotSettings(this._store);

  final SecretStore _store;

  static const _sigQtyKey = 'tane.social.wot.sigQty';
  static const _stepMaxKey = 'tane.social.wot.stepMax';
  static const _validityDaysKey = 'tane.social.wot.validityDays';

  /// The active parameters (any unset field falls back to the Duniter default).
  Future<WotParams> params() async {
    const base = WotParams.duniter;
    final sigQty = await _readInt(_sigQtyKey) ?? base.sigQty;
    final stepMax = await _readInt(_stepMaxKey) ?? base.stepMax;
    final validityDays =
        await _readInt(_validityDaysKey) ?? base.sigValidity.inDays;
    return WotParams(
      sigQty: sigQty,
      stepMax: stepMax,
      sigValidity: Duration(days: validityDays),
    );
  }

  Future<void> save(WotParams params) async {
    await _store.write(_sigQtyKey, '${params.sigQty}');
    await _store.write(_stepMaxKey, '${params.stepMax}');
    await _store.write(_validityDaysKey, '${params.sigValidity.inDays}');
  }

  /// Restores the Ğ1 reference values.
  Future<void> reset() => save(WotParams.duniter);

  Future<int?> _readInt(String key) async {
    final raw = await _store.read(key);
    if (raw == null || raw.isEmpty) return null;
    return int.tryParse(raw);
  }
}
