import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../repositories/otp_repository.dart';

part 'verify_otp_event.dart';
part 'verify_otp_state.dart';

class VerifyOtpBloc extends Bloc<VerifyOtpEvent, VerifyOtpState> {
  final OtpRepository _otpRepository;

  VerifyOtpBloc({OtpRepository? otpRepository})
      : _otpRepository = otpRepository ?? OtpRepository(),
        super(const VerifyOtpState()) {
    on<OtpChanged>(_onOtpChanged);
    on<VerifyOtpSubmitted>(_onVerifyOtpSubmitted);
  }

  void _onOtpChanged(OtpChanged event, Emitter<VerifyOtpState> emit) {
    emit(state.copyWith(otp: event.otp));
  }

  Future<void> _onVerifyOtpSubmitted(
    VerifyOtpSubmitted event,
    Emitter<VerifyOtpState> emit,
  ) async {
    emit(state.copyWith(status: VerifyOtpStatus.loading, errorMessage: null));

    try {
      await _otpRepository.verifyOtp(
        emailAddress: event.emailAddress,
        otp: event.otp,
      );

      emit(state.copyWith(status: VerifyOtpStatus.success));
    } catch (e) {
      emit(state.copyWith(
        status: VerifyOtpStatus.failure,
        errorMessage: e.toString().replaceAll('Exception: ', ''),
      ));
    }
  }
}