import 'package:flutter_secure_storage/flutter_secure_storage.dart';

/// `first_unlock` accessibility so the token can be read during background
/// requests (telemetry heartbeat, push-triggered syncs) after the first device
/// unlock following a reboot. The keychain default (`whenUnlocked`) throws
/// `-25308 errSecInteractionNotAllowed` when the device is locked.
const IOSOptions _mcIosOptions = IOSOptions(
  accessibility: KeychainAccessibility.first_unlock,
);

/// Persists the Marianum-Connect bearer token in the platform keystore. Kept
/// separate from `AccountData` because the username/password live on (Nextcloud
/// + MHSL still need them) while the MC token is short-lived and per-endpoint.
class MarianumConnectTokenStorage {
  static const _tokenKey = 'mc_bearer_token';
  static const _tokenIdKey = 'mc_token_id';
  static const _expiresAtKey = 'mc_token_expires_at';

  final FlutterSecureStorage _storage;

  const MarianumConnectTokenStorage([
    this._storage = const FlutterSecureStorage(iOptions: _mcIosOptions),
  ]);

  Future<String?> readToken() => _storage.read(key: _tokenKey);

  Future<String?> readTokenId() => _storage.read(key: _tokenIdKey);

  Future<DateTime?> readExpiresAt() async {
    final raw = await _storage.read(key: _expiresAtKey);
    if (raw == null || raw.isEmpty) return null;
    return DateTime.tryParse(raw);
  }

  Future<void> write({
    required String token,
    required String tokenId,
    required DateTime? expiresAt,
  }) async {
    await _storage.write(key: _tokenKey, value: token);
    await _storage.write(key: _tokenIdKey, value: tokenId);
    await _storage.write(
      key: _expiresAtKey,
      value: expiresAt?.toIso8601String() ?? '',
    );
  }

  Future<void> clear() async {
    await _storage.delete(key: _tokenKey);
    await _storage.delete(key: _tokenIdKey);
    await _storage.delete(key: _expiresAtKey);
  }
}
