export class UpdateUserProfileCommandHandler {
  constructor(userRepository) {
    this.userRepository = userRepository;
  }

  async handle(command) {
    const user = await this.userRepository.findById(command.userId);
    if (!user) {
      throw new Error('User not found');
    }

    const updateData = {};
    if (command.name && command.name.trim()) updateData.name = command.name.trim();
    if (command.email && command.email.trim()) updateData.email = command.email.trim();

    // Check if email is already taken by another user
    if (updateData.email && updateData.email !== user.email) {
      const existingUser = await this.userRepository.findByEmail(updateData.email);
      if (existingUser) {
        throw new Error('Email is already taken');
      }
    }

    return await this.userRepository.update(command.userId, updateData);
  }
}
