import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../domain/usecases/change_password_usecase.dart';
import 'change_password_event.dart';
import 'change_password_state.dart';

class ChangePasswordBloc
    extends Bloc<ChangePasswordEvent, ChangePasswordState> {
  final ChangePasswordUseCase changePasswordUseCase;

  ChangePasswordBloc({required this.changePasswordUseCase})
    : super(const ChangePasswordInitial()) {
    on<ChangePasswordSubmitted>(_onChangePasswordSubmitted);
    on<ChangePasswordReset>(_onChangePasswordReset);
  }

  Future<void> _onChangePasswordSubmitted(
    ChangePasswordSubmitted event,
    Emitter<ChangePasswordState> emit,
  ) async {
    emit(const ChangePasswordLoading());

    final result = await changePasswordUseCase(event.request);

    result.fold((failure) => emit(ChangePasswordError(failure.message)), (
      response,
    ) {
      if (response.isSuccess) {
        emit(ChangePasswordSuccess(response.message));
      } else {
        emit(ChangePasswordError(response.message));
      }
    });
  }

  void _onChangePasswordReset(
    ChangePasswordReset event,
    Emitter<ChangePasswordState> emit,
  ) {
    emit(const ChangePasswordInitial());
  }
}
