import 'package:flutter_bloc/flutter_bloc.dart'; import '../../data/repositories/auth_repository.dart'; import 'auth_event.dart'; import 'auth_state.dart'; class AuthBloc extends Bloc { final AuthRepository _repository; AuthBloc(this._repository) : super(AuthInitial()) { on(_onStarted); on(_onLoggedIn); on(_onLoggedOut); on(_onSessionInvalidated); } Future _onStarted(AuthStarted event, Emitter emit) async { emit(AuthLoading()); try { final refreshToken = await _repository.getRefreshToken(); if (refreshToken != null) { final response = await _repository.refreshSession(refreshToken); emit( AuthAuthenticated( user: AuthUser(id: response.user.id, phone: response.user.phone), ), ); return; } emit( const AuthUnauthenticated(reason: AuthUnauthenticatedReason.signedOut), ); } catch (_) { try { await _repository.clearSessionLocalOnly(); } catch (_) { // Keep state convergence even when storage cleanup fails. } finally { emit( const AuthUnauthenticated( reason: AuthUnauthenticatedReason.startupRecoveryFailed, ), ); } } } void _onLoggedIn(AuthLoggedIn event, Emitter emit) { emit(AuthAuthenticated(user: event.user)); } Future _onLoggedOut( AuthLoggedOut event, Emitter emit, ) async { try { await _repository.deleteSession(); } catch (_) { // Keep state convergence even when logout cleanup fails. } finally { emit( const AuthUnauthenticated(reason: AuthUnauthenticatedReason.signedOut), ); } } Future _onSessionInvalidated( AuthSessionInvalidated event, Emitter emit, ) async { try { await _repository.clearSessionLocalOnly(); } catch (_) { // Keep state convergence even when local cleanup fails. } finally { emit( const AuthUnauthenticated(reason: AuthUnauthenticatedReason.expired), ); } } }