using Domain.Exceptions; using Features.Auth.Dtos; using Features.Auth.Identity; using MediatR; using Microsoft.AspNetCore.Identity; namespace Features.Auth.Commands.UpdateUsername; /// Handles via . public class UpdateUsernameHandler(UserManager userManager) : IRequestHandler { /// Thrown when the account does not exist. /// Thrown when the requested username is already taken. public async Task Handle( UpdateUsernameCommand request, CancellationToken cancellationToken ) { ApplicationUser user = await userManager.FindByIdAsync(request.UserAccountId.ToString()) ?? throw new NotFoundException("User account not found"); IdentityResult result = await userManager.SetUserNameAsync(user, request.NewUsername); if (!result.Succeeded) { if (result.Errors.Any(e => e.Code == "DuplicateUserName")) throw new ConflictException("Username already exists"); throw new ConflictException(string.Join("; ", result.Errors.Select(e => e.Description))); } return new UpdateUsernamePayload(user.Id, user.UserName); } }