import 'package:bloc/bloc.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'app_version_event.dart';
import 'app_version_state.dart';

/// The AppVersionBloc class that handles app version-related events and states.
class AppVersionBloc extends Bloc<AppVersionEvent, AppVersionState> {
  AppVersionBloc() : super(AppVersionInitial()) {
    // Define the event handler for the LoadAppVersion event.
    on<LoadAppVersion>(_onLoadAppVersion);
  }

  /// The event handler for the LoadAppVersion event.
  Future<void> _onLoadAppVersion(
      LoadAppVersion event, Emitter<AppVersionState> emit) async {
    try {
      // Get the package info from the PackageInfoPlus package.
      final packageInfo = await PackageInfo.fromPlatform();

      // Extract the app version from the package info.
      final version = packageInfo.version;
      // Emit the AppVersionLoaded state with the app version.
      emit(AppVersionLoaded(version));
    } catch (e) {
      // Emit the AppVersionError state with an error message.
      emit(const AppVersionError('Failed to fetch app version'));
    }
  }
}
