import 'package:flutter_bloc/flutter_bloc.dart'; import 'dart:developer' as dev; import '../../domain/usecase/get_notifications_usecase.dart'; import '../event/notifications_event.dart'; import '../state/notifications_state.dart'; class NotificationsBloc extends Bloc { final GetNotificationsUsecase _getNotificationsUsecase; NotificationsBloc(this._getNotificationsUsecase) : super(const NotificationsState()) { on(_onFetchRequested); on(_onLoadMoreRequested); } Future _onFetchRequested( NotificationsFetchRequested event, Emitter emit, ) async { if (event.page == 1) { emit(state.copyWith(status: NotificationsStatus.loading)); } try { final result = await _getNotificationsUsecase( page: event.page, pageSize: 100, ); final newNotifications = event.page == 1 ? result.notifications : [...state.notifications, ...result.notifications]; emit(state.copyWith( status: NotificationsStatus.success, notifications: newNotifications, currentPage: result.pagination.currentPage, totalPages: result.pagination.lastPage, hasMore: result.pagination.currentPage < result.pagination.lastPage, isLoadingMore: false, )); } catch (e) { dev.log('NotificationsBloc: Ошибка загрузки: $e'); emit(state.copyWith( status: event.page == 1 ? NotificationsStatus.failure : NotificationsStatus.success, errorMessage: event.page == 1 ? e.toString() : null, isLoadingMore: false, )); } } Future _onLoadMoreRequested( NotificationsLoadMoreRequested event, Emitter emit, ) async { if (!state.hasMore || state.isLoadingMore) return; emit(state.copyWith(isLoadingMore: true)); final nextPage = state.currentPage + 1; add(NotificationsFetchRequested(page: nextPage)); } }