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 'logout_event.dart';
part 'logout_state.dart';
part 'logout_bloc.freezed.dart';

@injectable
class LogoutBloc extends Bloc<LogoutEvent, LogoutState> {
  final IAuthRepository _authRepository;
  LogoutBloc(this._authRepository) : super(LogoutState.initial()) {
    on<LogoutEvent>(_onLogoutEvent);
  }

  Future<void> _onLogoutEvent(LogoutEvent event, Emitter<LogoutState> emit) {
    return event.map(
      logout: (e) async {
        Either<AuthFailure, Unit>? failureOrSuccess;
        emit(
          state.copyWith(isLoggingOut: true, logoutFailureOrSuccess: none()),
        );

        failureOrSuccess = await _authRepository.logout();

        emit(
          state.copyWith(
            isLoggingOut: false,
            logoutFailureOrSuccess: optionOf(failureOrSuccess),
          ),
        );
      },
    );
  }
}
