using Domain.Exceptions;
using Features.Auth.Dtos;
using Features.Auth.Identity;
using MediatR;
using Microsoft.AspNetCore.Identity;
namespace Features.Auth.Commands.UpdateProfile;
///
/// Handles via . First/last name
/// and date of birth aren't tracked by any Identity-specific store interface, so the mutated
/// is saved directly through .
///
public class UpdateProfileHandler(UserManager userManager)
: IRequestHandler
{
/// Thrown when the account does not exist.
/// Thrown when the update otherwise fails.
public async Task Handle(
UpdateProfileCommand request,
CancellationToken cancellationToken
)
{
ApplicationUser user =
await userManager.FindByIdAsync(request.UserAccountId.ToString())
?? throw new NotFoundException("User account not found");
user.FirstName = request.FirstName;
user.LastName = request.LastName;
user.DateOfBirth = request.DateOfBirth;
IdentityResult result = await userManager.UpdateAsync(user);
if (!result.Succeeded)
throw new ConflictException(string.Join("; ", result.Errors.Select(e => e.Description)));
return new UpdateProfilePayload(user.Id, user.FirstName, user.LastName, user.DateOfBirth);
}
}