using Heimdall.Application.Common; using Heimdall.Application.Common.Persistence; using Heimdall.Application.DTOs; using Heimdall.Domain.Entities; using MediatR; using Heimdall.Application.Services; namespace Heimdall.Application.Users.Commands.CreateUser; public class CreateUserHandler : IRequestHandler> { private readonly IIdentityAccountService _userManager; private readonly IUserRepository _repository; public CreateUserHandler(IIdentityAccountService userManager, IUserRepository repository) { _userManager = userManager; _repository = repository; } public async Task> Handle(CreateUserCommand command, CancellationToken ct) { var existing = await _userManager.FindByEmailAsync(command.Email, ct).ConfigureAwait(false); if (existing is not null) return ServiceResult.Conflict("Email already registered"); var user = new IdentityAccount { UserName = command.Email, Email = command.Email, DisplayName = command.DisplayName }; var result = await _userManager.CreateAsync(user, command.Password, ct).ConfigureAwait(false); if (!result.Succeeded) return ServiceResult.Failure( string.Join(", ", result.ErrorCodes)); var roles = command.Roles is { Count: > 0 } ? command.Roles : new List { "Viewer" }; var assignment = await _userManager.AddToRolesAsync(user, roles, ct).ConfigureAwait(false); if (!assignment.Succeeded) { await _userManager.DeleteAsync(user, ct).ConfigureAwait(false); return ServiceResult.Failure("Unable to assign requested account roles"); } await _repository.AddAuditLogAsync(command.ActorId, "UserCreated", "User", user.Id.ToString(), null, null, ct); var response = await _repository.GetByIdAsync(user.Id, ct).ConfigureAwait(false); return ServiceResult.Success(response!); } }