import 'package:bloc/bloc.dart';
import 'package:enaklo_pos/data/datasources/category_remote_datasource.dart';
import 'package:enaklo_pos/data/models/response/category_response_model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'category_loader_event.dart';
part 'category_loader_state.dart';
part 'category_loader_bloc.freezed.dart';

class CategoryLoaderBloc
    extends Bloc<CategoryLoaderEvent, CategoryLoaderState> {
  final CategoryRemoteDatasource _datasource;
  CategoryLoaderBloc(this._datasource) : super(CategoryLoaderState.initial()) {
    on<_Get>((event, emit) async {
      emit(const _Loading());
      final result = await _datasource.getCategories(limit: 50);
      result.fold(
        (l) => emit(_Error(l)),
        (r) async {
          List<CategoryModel> categories = r.data.categories;
          categories.insert(
            0,
            CategoryModel(
              id: "",
              name: 'Semua',
              organizationId: '',
              businessType: '',
              metadata: {},
              createdAt: DateTime.now(),
              updatedAt: DateTime.now(),
            ),
          );
          emit(_Loaded(categories, null));
        },
      );
    });
    on<_SetCategoryId>((event, emit) async {
      var currentState = state as _Loaded;

      emit(_Loaded(currentState.categories, event.categoryId));
    });
  }
}
