import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../../core/network/dio_client.dart'; import '../domain/uom.dart'; class UomsNotifier extends AsyncNotifier> { List _allUoms = []; @override Future> build() async { return _fetchUoms(); } Future> _fetchUoms() async { final response = await DioClient().dio.get('/inventory/uom').timeout( const Duration(seconds: 5), onTimeout: () => throw Exception('Connection timed out'), ); if (response.data == null || response.data.toString().isEmpty) { _allUoms = []; return []; } final list = (response.data as List).map((e) => UnitOfMeasure.fromJson(e)).toList(); _allUoms = list; return list; } void search(String query) { if (query.isEmpty) { state = AsyncValue.data(_allUoms); return; } final lowerQuery = query.toLowerCase(); final filtered = _allUoms.where((uom) => uom.name.toLowerCase().contains(lowerQuery) || (uom.abbreviation?.toLowerCase().contains(lowerQuery) ?? false) ).toList(); state = AsyncValue.data(filtered); } Future fetchUoms() async { try { final data = await _fetchUoms(); state = AsyncValue.data(data); } catch (e, stack) { state = AsyncValue.error(e, stack); } } Future createUom(UnitOfMeasure uom) async { try { final response = await DioClient().dio.post('/inventory/uom', data: uom.toJson()); final newUom = UnitOfMeasure.fromJson(response.data); if (state is AsyncData) { _allUoms = [..._allUoms, newUom]; state = AsyncValue.data([...state.value!, newUom]); } else { await fetchUoms(); } } catch (e) { throw Exception('Failed to create UOM: $e'); } } Future updateUom(int id, UnitOfMeasure uom) async { try { final response = await DioClient().dio.put('/inventory/uom/$id', data: uom.toJson()); final updatedUom = UnitOfMeasure.fromJson(response.data); if (state is AsyncData) { _allUoms = _allUoms.map((e) => e.id == id ? updatedUom : e).toList(); state = AsyncValue.data( state.value!.map((e) => e.id == id ? updatedUom : e).toList(), ); } } catch (e) { throw Exception('Failed to update UOM: $e'); } } Future deleteUom(int id) async { try { await DioClient().dio.delete('/inventory/uom/$id'); if (state is AsyncData) { _allUoms = _allUoms.where((e) => e.id != id).toList(); state = AsyncValue.data( state.value!.where((e) => e.id != id).toList(), ); } } catch (e) { throw Exception('Failed to delete UOM: $e'); } } } final uomsProvider = AsyncNotifierProvider>(() { return UomsNotifier(); });