import 'package:im_app/domain/entities/user.dart';
import 'package:im_app/domain/repositories/user_repository.dart';

/// 批量插入用户用例
///
/// ## 职责
/// - 封装用户插入的业务规则
/// - 去重（uid 相同时保留最后一个）
/// - 分批插入，避免单次写入过大
///
/// ## 数据流
/// ```
/// ViewModel
///   → InsertUsersUseCase.execute(users)
///     → 去重
///     → UserRepository.saveUsers(chunk)  ← 分批写入
///     → onProgress(completed, total)     ← 可选进度回调
///   ← 实际插入数量
/// ```
class InsertUsersUseCase {
  final UserRepository _repo;
  static const _chunkSize = 200;

  InsertUsersUseCase({required UserRepository userRepository})
    : _repo = userRepository;

  /// 批量插入用户
  ///
  /// [users] 要插入的用户列表
  /// [onProgress] 可选回调，每批完成后触发
  ///
  /// 返回实际插入数量
  Future<int> execute(
    List<User> users, {
    void Function(int completed, int total, List<User> chunk)? onProgress,
  }) async {
    if (users.isEmpty) return 0;

    final deduped = {for (final u in users) u.uid: u}.values.toList();
    final total = deduped.length;
    int completed = 0;

    while (completed < total) {
      final end = (completed + _chunkSize).clamp(0, total);
      final chunk = deduped.sublist(completed, end);

      await _repo.insertOrReplaceUsers(chunk);
      completed += chunk.length;

      onProgress?.call(completed, total, chunk);
    }

    return completed;
  }
}
