import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow_core/core.dart';
import '../../domain/usecases/get_profile_usecase.dart';
import '../../domain/usecases/sign_out_usecase.dart';
import 'profile_state.dart';

/// Cubit for managing the Profile feature state.
///
/// Handles loading profile data and user sign-out actions.
class ProfileCubit extends Cubit<ProfileState>
    with BlocErrorHandler<ProfileState> {
  final GetProfileUseCase _getProfileUseCase;
  final SignOutUseCase _signOutUseCase;

  /// Creates a [ProfileCubit] with the required use cases.
  ProfileCubit(this._getProfileUseCase, this._signOutUseCase)
    : super(const ProfileState());

  /// Loads the staff member's profile.
  ///
  /// Emits [ProfileStatus.loading] while fetching data,
  /// then [ProfileStatus.loaded] with the profile data on success,
  /// or [ProfileStatus.error] if an error occurs.
  Future<void> loadProfile() async {
    emit(state.copyWith(status: ProfileStatus.loading));

    await handleError(
      emit: emit,
      action: () async {
        final profile = await _getProfileUseCase();
        emit(state.copyWith(status: ProfileStatus.loaded, profile: profile));
      },
      onError:
          (String errorKey) =>
              state.copyWith(status: ProfileStatus.error, errorMessage: errorKey),
    );
  }

  /// Signs out the current user.
  ///
  /// Delegates to the sign-out use case which handles session cleanup
  /// and navigation.
  Future<void> signOut() async {
    if (state.status == ProfileStatus.loading) {
      return;
    }

    emit(state.copyWith(status: ProfileStatus.loading));

    await handleError(
      emit: emit,
      action: () async {
        await _signOutUseCase();
        emit(state.copyWith(status: ProfileStatus.signedOut));
      },
      onError: (String _) {
        // For sign out errors, we might want to just proceed or show error
        // Current implementation was silent catch, let's keep it robust but consistent
        // If we want to force navigation even on error, we would do it here
        // But usually handleError emits the error state.
        // Let's stick to standard error reporting for now.
        return state.copyWith(status: ProfileStatus.error);
      },
    );
  }
}

