import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:im_app/features/chat/usecases/delete_users_use_case.dart';
import 'package:im_app/features/chat/usecases/insert_users_use_case.dart';
import 'package:im_app/features/chat/usecases/update_users_use_case.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:im_app/app/di/db_provider.dart';
import 'package:im_app/data/repositories/user_repository_impl.dart';
import 'package:im_app/domain/entities/user.dart';
import 'package:im_app/domain/repositories/user_repository.dart';

part 'user_provider.g.dart';

// ── Repository ────────────────────────────────────────────────────────────────

@riverpod
UserRepository userRepository(Ref ref) {
  return UserRepositoryImpl(ref.watch(storageSdkProvider));
}

// ── Use Cases ─────────────────────────────────────────────────────────────────

/// 批量插入用户用例 Provider
///
/// 封装去重 + 分批插入逻辑，ViewModel 只需传入用户列表
final insertUsersUseCaseProvider = Provider<InsertUsersUseCase>((ref) {
  return InsertUsersUseCase(userRepository: ref.read(userRepositoryProvider));
});

/// 批量更新用户用例 Provider
///
/// 取前10条，随机生成昵称，批量更新到 DB
final updateUsersUseCaseProvider = Provider<UpdateUsersUseCase>((ref) {
  return UpdateUsersUseCase(userRepository: ref.read(userRepositoryProvider));
});

/// 删除前10个用户用例 Provider
///
/// 取前10条，按 uid 逐条删除
final deleteUsersUseCaseProvider = Provider<DeleteUsersUseCase>((ref) {
  return DeleteUsersUseCase(userRepository: ref.read(userRepositoryProvider));
});

// ── Streams ───────────────────────────────────────────────────────────────────

@riverpod
Stream<List<User>> users(Ref ref, Set<int> uids) {
  return ref.watch(userRepositoryProvider).watchUsers(uids.toList());
}

@riverpod
Stream<List<User>> allUsers(Ref ref) {
  return ref.watch(userRepositoryProvider).watchAllUsers();
}
