import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import '../../../data/dtos/hero_dto.dart';
import '../../../data/repositories/hero_repository.dart';

// Events
abstract class HeroListEvent extends Equatable {
  @override
  List<Object> get props => [];
}

class FetchHeroes extends HeroListEvent {}

// States
abstract class HeroListState extends Equatable {
  @override
  List<Object> get props => [];
}

class HeroListInitial extends HeroListState {}

class HeroListLoading extends HeroListState {}

class HeroListLoaded extends HeroListState {
  final List<HeroDto> heroes;

  HeroListLoaded(this.heroes);

  @override
  List<Object> get props => [heroes];
}

class HeroListError extends HeroListState {
  final String message;

  HeroListError(this.message);

  @override
  List<Object> get props => [message];
}

// BLoC
class HeroListBloc extends Bloc<HeroListEvent, HeroListState> {
  final HeroRepository heroRepository;

  HeroListBloc(this.heroRepository) : super(HeroListInitial()) {
    on<FetchHeroes>((event, emit) async {
      emit(HeroListLoading());
      try {
        final heroes = await heroRepository.getHeroes();
        print('Heroes loaded: ${heroes.map((hero) => hero.name).toList()}'); // Отладочный вывод
        emit(HeroListLoaded(heroes));
      } catch (e) {
        print('Error loading heroes: $e'); // Отладочный вывод ошибок
        emit(HeroListError(e.toString()));
      }
    });
  }
}
