import 'package:bloc/bloc.dart';
import 'package:dartz/dartz.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:injectable/injectable.dart';

import '../../../domain/auth/auth.dart';

part 'verify_form_event.dart';
part 'verify_form_state.dart';
part 'verify_form_bloc.freezed.dart';

@injectable
class VerifyFormBloc extends Bloc<VerifyFormEvent, VerifyFormState> {
  final IAuthRepository _repository;
  VerifyFormBloc(this._repository) : super(VerifyFormState.initial()) {
    on<VerifyFormEvent>(_onVerifyFormEvent);
  }

  Future<void> _onVerifyFormEvent(
    VerifyFormEvent event,
    Emitter<VerifyFormState> emit,
  ) {
    return event.map(
      registrationTokenChanged: (e) async {
        emit(
          state.copyWith(
            registrationToken: e.registrationToken,
            failureOrVerifyOption: none(),
          ),
        );
      },
      otpCodeChanged: (e) async {
        emit(state.copyWith(otpCode: e.otpCode, failureOrVerifyOption: none()));
      },
      submitted: (e) async {
        Either<AuthFailure, Verify>? failureOrVerify;
        emit(state.copyWith(isSubmitting: true, failureOrVerifyOption: none()));

        final otpCodeValid = state.otpCode.isNotEmpty;
        final registrationTokenValid = state.registrationToken.isNotEmpty;

        if (registrationTokenValid && otpCodeValid) {
          failureOrVerify = await _repository.verify(
            registrationToken: state.registrationToken,
            otpCode: state.otpCode,
          );
          emit(
            state.copyWith(
              isSubmitting: false,
              failureOrVerifyOption: optionOf(failureOrVerify),
            ),
          );
        }
        emit(state.copyWith(showErrorMessages: true, isSubmitting: false));
      },
    );
  }
}
