import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../services/api_client.dart'; class AuthState { final bool isAuthenticated; final Map? user; final bool isLoading; final String? error; const AuthState({ this.isAuthenticated = false, this.user, this.isLoading = false, this.error, }); AuthState copyWith({ bool? isAuthenticated, Map? user, bool? isLoading, String? error, }) { return AuthState( isAuthenticated: isAuthenticated ?? this.isAuthenticated, user: user ?? this.user, isLoading: isLoading ?? this.isLoading, error: error, ); } } class AuthNotifier extends StateNotifier> { final ApiClient _apiClient; AuthNotifier(this._apiClient) : super(const AsyncValue.loading()) { _checkSession(); } Future _checkSession() async { try { final session = await _apiClient.getSession(); if (session != null && session['user'] != null) { state = AsyncValue.data(AuthState( isAuthenticated: true, user: session['user'], )); } else { state = const AsyncValue.data(AuthState(isAuthenticated: false)); } } catch (e) { state = const AsyncValue.data(AuthState(isAuthenticated: false)); } } Future signUp({ required String email, required String password, required String name, }) async { state = const AsyncValue.loading(); try { final result = await _apiClient.signUp( email: email, password: password, name: name, ); state = AsyncValue.data(AuthState( isAuthenticated: true, user: result['user'], )); } catch (e) { state = AsyncValue.data(AuthState( isAuthenticated: false, error: e.toString(), )); rethrow; } } Future signIn({ required String email, required String password, }) async { state = const AsyncValue.loading(); try { final result = await _apiClient.signIn( email: email, password: password, ); state = AsyncValue.data(AuthState( isAuthenticated: true, user: result['user'], )); } catch (e) { state = AsyncValue.data(AuthState( isAuthenticated: false, error: e.toString(), )); rethrow; } } Future signOut() async { try { await _apiClient.signOut(); } finally { state = const AsyncValue.data(AuthState(isAuthenticated: false)); } } } final authStateProvider = StateNotifierProvider>((ref) { final apiClient = ref.watch(apiClientProvider); return AuthNotifier(apiClient); });