using MediatR; using Mws.Application.Common; using Mws.Application.Permissions; namespace Mws.Application.Accounts; public record DeleteAccountCommand(Guid ActorUserId, Guid Id) : IRequest; public class DeleteAccountHandler(IUnitOfWork uow, IPermissionService permissions) : IRequestHandler { private const string Screen = "accounts"; public async Task Handle(DeleteAccountCommand command, CancellationToken ct) { await permissions.EnsureAsync(command.ActorUserId, Screen, PermissionAction.Delete, ct); var user = await uow.Users.GetByIdAsync(command.Id, ct) ?? throw new NotFoundException("Account not found"); var soleOwnerProjectIds = await uow.Projects.GetOwnedProjectIdsAsync(command.Id, ct); foreach (var projectId in soleOwnerProjectIds) { var ownerCount = await uow.Projects.CountOwnersAsync(projectId, ct); if (ownerCount <= 1) { throw new BadRequestException("Cannot delete an account that is the sole owner of a project"); } } uow.Users.Remove(user); await uow.SaveChangesAsync(ct); } }