import 'package:hive/hive.dart';
import '../../models/global_state_model.dart';

class CachedData<T> {
  final T data;
  final DateTime cachedAt;
  final Duration expiry;

  CachedData({
    required this.data,
    required this.cachedAt,
    this.expiry = const Duration(minutes: 5),
  });

  bool get isExpired => DateTime.now().difference(cachedAt) > expiry;
}

class CacheManager {
  static const String _globalStateKey = 'global_state';
  Box? _box;

  Future<void> init() async {
    _box = await Hive.openBox('mining_cache');
  }

  Future<CachedData<GlobalStateModel>?> getGlobalState() async {
    if (_box == null) await init();
    final cached = _box?.get(_globalStateKey);
    if (cached == null) return null;

    try {
      return CachedData(
        data: GlobalStateModel.fromJson(Map<String, dynamic>.from(cached['data'])),
        cachedAt: DateTime.parse(cached['cachedAt']),
      );
    } catch (e) {
      return null;
    }
  }

  Future<void> cacheGlobalState(GlobalStateModel state) async {
    if (_box == null) await init();
    await _box?.put(_globalStateKey, {
      'data': {
        'currentPrice': state.currentPrice,
        'priceChange24h': state.priceChange24h,
        'totalDistributed': state.totalDistributed,
        'totalBurned': state.totalBurned,
        'circulationPool': state.circulationPool,
        'networkContribution': state.networkContribution,
        'eraNumber': state.eraNumber,
        'remainingDistribution': state.remainingDistribution,
        'updatedAt': state.updatedAt.toIso8601String(),
      },
      'cachedAt': DateTime.now().toIso8601String(),
    });
  }

  Future<void> clear() async {
    await _box?.clear();
  }
}
