import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'api_client.dart'; const _ttl = Duration(minutes: 5); class _OptionsCache { final Map data; final DateTime fetchedAt; const _OptionsCache(this.data, this.fetchedAt); bool get expired => DateTime.now().difference(fetchedAt) > _ttl; } class InventoryOptionsCacheNotifier extends StateNotifier>> { InventoryOptionsCacheNotifier(this._api) : super(const AsyncValue.loading()) { _fetch(); } final ApiClient _api; _OptionsCache? _cache; Future _fetch() async { if (_cache != null && !_cache!.expired) { state = AsyncValue.data(_cache!.data); return; } state = const AsyncValue.loading(); final response = await _api.inventoryOptions(); if (response.success && response.data != null) { _cache = _OptionsCache(response.data!, DateTime.now()); state = AsyncValue.data(_cache!.data); } else { state = AsyncValue.error( response.message ?? 'Error cargando opciones', StackTrace.current, ); } } Future refresh() => _fetch(); List> get warehouses { final data = state.valueOrNull; if (data == null) return const []; return List>.from( (data['warehouses'] as List?) ?? const [], ); } } final inventoryOptionsCacheProvider = StateNotifierProvider< InventoryOptionsCacheNotifier, AsyncValue>>((ref) { return InventoryOptionsCacheNotifier(ref.watch(apiClientProvider)); });