import 'package:flutter_bloc/flutter_bloc.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> {
  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));

    try {
      final profile = await _getProfileUseCase();
      emit(state.copyWith(
        status: ProfileStatus.loaded,
        profile: profile,
      ));
    } catch (e) {
      emit(state.copyWith(
        status: ProfileStatus.error,
        errorMessage: e.toString(),
      ));
    }
  }

  /// 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));

    try {
      await _signOutUseCase();
      emit(state.copyWith(status: ProfileStatus.signedOut));
    } catch (e) {
      // Error handling can be added here if needed
      // For now, we let the navigation happen regardless
    }
  }
}
