import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_app/core/providers/app_provider.dart';
import 'package:niogu_app/features/goods/units/data/unit_repository_impl.dart';
import 'package:niogu_app/features/goods/units/domain/entities/unit.dart';
import 'package:niogu_app/features/goods/units/domain/repositories/i_unit_repository.dart';
import 'package:niogu_app/features/goods/units/presentation/controller/unit_controller.dart';

final unitRepositoryProvider = Provider<IUnitRepository>((ref) {
  final appDatabase = ref.watch(appDatabaseProvider);
  return UnitRepositoryImpl(appDatabase);
});

final unitStreamProvider = StreamProvider.autoDispose<List<Unit>>((ref) {
  final unitRepository = ref.watch(unitRepositoryProvider);
  return unitRepository.watchUnits();
});

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

final validateUnitProvider = Provider.autoDispose<bool>((ref) {
  final unitStreamAsync = ref.watch(unitStreamProvider);
  final unitSearchAsync = ref.watch(unitSearchProvider);

  return unitStreamAsync.maybeWhen(
    data: (units) {
      return units.where((unit) {
        return unit.name.trim().toLowerCase() ==
            unitSearchAsync.trim().toLowerCase();
      }).isEmpty;
    },
    orElse: () => true,
  );
});

final unitControllerProvider = AsyncNotifierProvider.autoDispose<UnitController, void>(
  UnitController.new,
);
