import 'package:food_delivery_client/feature/auth/domain/usecases/register_usecase.dart';
import 'package:food_delivery_client/feature/common/presentation/widgets/w_toastification.dart';
import 'package:food_delivery_client/food_delivery_client.dart';

part 'register_event.dart';

part 'register_state.dart';

part 'register_bloc.freezed.dart';

@injectable
class RegisterBloc extends Bloc<RegisterEvent, RegisterState> {
  final RegisterUseCase _registerUseCase;

  RegisterBloc(this._registerUseCase) : super(const RegisterState()) {
    on<_Loaded>(_onLoaded);
  }

  Future<void> _onLoaded(_Loaded event, Emitter<RegisterState> emit) async {
    emit(state.copyWith(status: RequestStatus.loading));

    final response = await _registerUseCase.call(event.params);

    response.fold(
      (l) {
        showErrorToast(l.errorMessage);
        emit(state.copyWith(status: RequestStatus.error));
      },
      (r) {
        showSuccessToast(r.message);
        emit(state.copyWith(status: RequestStatus.loaded));
      },
    );
  }
}
