using Heimdall.Application.Common; using Heimdall.Application.Common.Persistence; using Heimdall.Domain.Entities; using MediatR; using Heimdall.Application.Services; namespace Heimdall.Application.Users.Commands.DeleteUser; public class DeleteUserHandler : IRequestHandler { private readonly IIdentityAccountService _userManager; private readonly IUserRepository _repository; public DeleteUserHandler(IIdentityAccountService userManager, IUserRepository repository) { _userManager = userManager; _repository = repository; } public async Task Handle(DeleteUserCommand command, CancellationToken ct) { if (command.UserId == command.CurrentUserId) return ServiceResult.Failure("You cannot delete your own account.", 400); var user = await _userManager.FindByIdAsync(command.UserId, ct).ConfigureAwait(false); if (user is null) return ServiceResult.NotFound("User not found"); var roles = await _userManager.GetRolesAsync(user, ct).ConfigureAwait(false); if (roles.Contains("Admin")) { var adminCount = await _repository.CountAdminUsersAsync(ct).ConfigureAwait(false); if (adminCount <= 1) return ServiceResult.Failure("Cannot delete the last administrator. " + "Promote another user to Admin first.", 400); } await _repository.RemoveUserDataAsync(command.UserId, ct).ConfigureAwait(false); var result = await _userManager.DeleteAsync(user, ct).ConfigureAwait(false); if (!result.Succeeded) return ServiceResult.Failure( string.Join(", ", result.ErrorCodes)); await _repository.AddAuditLogAsync(command.CurrentUserId, "UserDeleted", "User", command.UserId.ToString(), null, null, ct); return ServiceResult.Success(); } }