import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../core/auth/auth_provider.dart'; import '../../shared/models/recipe.dart'; import '../../shared/models/saved_recipe.dart'; import 'recipe_service.dart'; // --------------------------------------------------------------------------- // Service provider // --------------------------------------------------------------------------- final recipeServiceProvider = Provider((ref) { return RecipeService(ref.read(apiClientProvider)); }); // --------------------------------------------------------------------------- // Recommendations // --------------------------------------------------------------------------- class RecommendationsNotifier extends StateNotifier>> { final RecipeService _service; RecommendationsNotifier(this._service) : super(const AsyncValue.loading()) { load(); } Future load({int count = 5}) async { state = const AsyncValue.loading(); state = await AsyncValue.guard( () => _service.getRecommendations(count: count), ); } } final recommendationsProvider = StateNotifierProvider>>((ref) { return RecommendationsNotifier(ref.read(recipeServiceProvider)); }); // --------------------------------------------------------------------------- // Saved recipes // --------------------------------------------------------------------------- class SavedRecipesNotifier extends StateNotifier>> { final RecipeService _service; SavedRecipesNotifier(this._service) : super(const AsyncValue.loading()) { load(); } Future load() async { state = const AsyncValue.loading(); state = await AsyncValue.guard(() => _service.getSavedRecipes()); } /// Saves [recipe] and reloads the list. Returns the saved record or null on error. Future save(Recipe recipe) async { try { final saved = await _service.saveRecipe(recipe); await load(); return saved; } catch (_) { return null; } } /// Removes the recipe with [id] optimistically and reverts on error. Future delete(String id) async { final previous = state; state = state.whenData( (list) => list.where((r) => r.id != id).toList(), ); try { await _service.deleteSavedRecipe(id); return true; } catch (_) { state = previous; return false; } } /// Returns true if any saved recipe has the same title. bool isSaved(String title) { return state.whenOrNull( data: (list) => list.any((r) => r.title == title), ) ?? false; } /// Returns the saved recipe ID for the given title, or null. String? savedId(String title) { return state.whenOrNull( data: (list) { try { return list.firstWhere((r) => r.title == title).id; } catch (_) { return null; } }, ); } } final savedRecipesProvider = StateNotifierProvider>>((ref) { return SavedRecipesNotifier(ref.read(recipeServiceProvider)); });