import 'package:dio/dio.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:frontend_eccp_mobile/app/core/services/crashlytics_service.dart';
import 'package:frontend_eccp_mobile/modules/profile/bloc/logout/logout_state.dart';
import 'package:frontend_eccp_mobile/modules/profile/data/repositories/profile_repository.dart';
import 'package:injectable/injectable.dart';

@injectable
class LogoutCubit extends Cubit<LogoutState> {
  LogoutCubit(this._repository) : super(LogoutInitial());

  final ProfileRepository _repository;

  Future<void> logout() async {
    emit(LogoutLoading());

    try {
      final response = await _repository.logout();

      if (response.status != 'success') {
        emit(LogoutFailure(response.message));
        return;
      }
      emit(LogoutSuccess());
    } on DioException catch (e) {
      emit(LogoutFailure(e.error?.toString()));
    } catch (e, s) {
      await CrashlyticsService.recordError(
        e,
        s,
        fatal: true,
        reason: 'Logout Unknown Error',
      );
      emit(const LogoutFailure());
    }
  }
}
