import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:proxibuy/data/models/categories/categories_model.dart';
import 'package:proxibuy/data/repositories/category_repository.dart';

part 'categories_state.dart';

class CategoriesCubit extends Cubit<CategoriesState> {
  CategoriesCubit() : super(CategoriesInitial());

  void updateCategories(List<CategoriesModel> newCategories) {
    emit(state.copyWith(categories: newCategories));
  }

  Future<void> getAllCategories() async {
    if (state.isLoading || state.currentPage > state.totalPages) return;
    if (state.currentPage == 1) {
      emit(CategoriesLoading());
    } else {
      emit(state.copyWith(isLoading: true));
    }
    try {
      final response =
          await CategoryRepository.fetchAll(page: state.currentPage);
      emit(CategoriesLoaded(
        categories: List.from(state.categories)..addAll(response.data ?? []),
        isLoading: false,
        currentPage: state.currentPage + 1,
        totalPages: response.meta?.totalPages ?? 1,
      ));
    } catch (e) {
      emit(CategoriesError(e.toString()));
    }
  }

  Future resetPagination() async {
    emit(CategoriesInitial());
  }
}
