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<NotificationsEvent, NotificationsState> {
  final GetNotificationsUsecase _getNotificationsUsecase;

  NotificationsBloc(this._getNotificationsUsecase) : super(const NotificationsState()) {
    on<NotificationsFetchRequested>(_onFetchRequested);
  }

  Future<void> _onFetchRequested(
      NotificationsFetchRequested event,
      Emitter<NotificationsState> emit,
      ) async {
    emit(state.copyWith(status: NotificationsStatus.loading));

    try {
      final notifications = await _getNotificationsUsecase();
      emit(state.copyWith(
        status: NotificationsStatus.success,
        notifications: notifications,
      ));
    } catch (e) {
      dev.log('NotificationsBloc: Ошибка загрузки: $e');
      emit(state.copyWith(
        status: NotificationsStatus.failure,
        errorMessage: e.toString(),
      ));
    }
  }
}