import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_app/core/providers/app_provider.dart';
import 'package:niogu_app/features/goods/products/data/repositories/category_repository_impl.dart';
import 'package:niogu_app/features/goods/products/domain/entities/category.dart';
import 'package:niogu_app/features/goods/products/domain/repositories/i_category_repository.dart';
import 'package:niogu_app/features/goods/products/presentation/controllers/category_controller.dart';

final categoryRepositoryProvider = Provider<ICategoryRepository>((ref) {
  final appDatabase = ref.watch(appDatabaseProvider);
  return CategoryRepositoryImpl(appDatabase);
});

final categoryStreamProvider = StreamProvider.autoDispose<List<Category>>((
  ref,
) {
  final categoryRepository = ref.watch(categoryRepositoryProvider);
  return categoryRepository.watchCategories();
});

final categorySearchProvider = StateProvider.autoDispose<String>((ref) => '');

final validateCategoryProvider = Provider.autoDispose<bool>((ref) {
  final categoryStreamAsync = ref.watch(categoryStreamProvider);
  final categorySearchAsync = ref.watch(categorySearchProvider);

  return categoryStreamAsync.maybeWhen(
    data: (categories) {
      return categories
          .where(
            (category) =>
                category.name.trim().toLowerCase() ==
                categorySearchAsync.trim().toLowerCase(),
          )
          .isEmpty;
    },
    orElse: () => true,
  );
});

final categoryControllerProvider =
    AsyncNotifierProvider.autoDispose<CategoryController, void>(
      CategoryController.new,
    );
