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_form_event.dart';
part 'logout_form_state.dart';
part 'logout_form_bloc.freezed.dart';

@injectable
class LogoutFormBloc extends Bloc<LogoutFormEvent, LogoutFormState> {
  final IAuthRepository _repository;

  LogoutFormBloc(this._repository) : super(LogoutFormState.initial()) {
    on<LogoutFormEvent>(_onLogoutFormEvent);
  }

  Future<void> _onLogoutFormEvent(
    LogoutFormEvent event,
    Emitter<LogoutFormState> emit,
  ) {
    return event.map(
      submitted: (e) async {
        emit(state.copyWith(isSubmitting: true, failureOrAuthOption: none()));
        final failureOrAuth = await _repository.logout();
        emit(
          state.copyWith(
            isSubmitting: false,
            failureOrAuthOption: optionOf(failureOrAuth),
          ),
        );
      },
    );
  }
}
