import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../core/network/dio_client.dart';
import '../models/asset/wallet_overview.dart';
import '../services/asset_service.dart';

/// 资产数据仓库（SSOT）
class AssetRepository {
  AssetRepository(this._service);

  final AssetService _service;

  // 内存缓存
  List<WalletOverview>? _cachedWalletOverview;
  DateTime? _lastFetched;

  static const _cacheDuration = Duration(seconds: 30);

  bool get _isCacheValid =>
      _lastFetched != null &&
      DateTime.now().difference(_lastFetched!) < _cacheDuration;

  /// 获取账户总览
  Future<List<WalletOverview>> getWalletOverview({
    bool forceRefresh = false,
  }) async {
    if (!forceRefresh && _isCacheValid && _cachedWalletOverview != null) {
      return _cachedWalletOverview!;
    }
    _cachedWalletOverview = await _service.getWalletOverview();
    _lastFetched = DateTime.now();
    return _cachedWalletOverview!;
  }

  /// 清除缓存
  void clearCache() {
    _cachedWalletOverview = null;
    _lastFetched = null;
  }
}

/// AssetRepository Provider
final assetRepositoryProvider = Provider<AssetRepository>((ref) {
  final dio = ref.watch(dioClientProvider);
  return AssetRepository(AssetService(dio));
});
