import 'package:food_delivery_client/feature/auth/domain/usecases/verify_phone_login_usecase.dart';
import 'package:food_delivery_client/feature/auth/domain/usecases/verify_phone_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 'verify_phone_event.dart';

part 'verify_phone_state.dart';

part 'verify_phone_bloc.freezed.dart';

@injectable
class VerifyPhoneBloc extends Bloc<VerifyPhoneEvent, VerifyPhoneState> {
  final VerifyPhoneNumberLoginUseCase _loginUseCase;
  final VerifyPhoneRegisterUseCase _registerUseCase;

  VerifyPhoneBloc(this._loginUseCase, this._registerUseCase)
    : super(const VerifyPhoneState()) {
    on<_VerifyPhoneRegister>(_onVerifyPhoneNumberRegister);
    on<_VerifyPhoneReset>(_onVerifyPhoneReset);
  }

  Future<void> _onVerifyPhoneNumberRegister(
    _VerifyPhoneRegister event,
    Emitter<VerifyPhoneState> 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));
      },
    );
  }

  Future<void> _onVerifyPhoneReset(
    _VerifyPhoneReset event,
    Emitter<VerifyPhoneState> emit,
  ) async {
    emit(state.copyWith(status: RequestStatus.loading));
    final response = await _loginUseCase.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));
      },
    );
  }
}
