using Brizco.Domain.Entities.Complexes; namespace Brizco.Repository.Handlers.Complex; public class DeleteComplexUserCommandHandler : IRequestHandler { private readonly IRepositoryWrapper _repositoryWrapper; public DeleteComplexUserCommandHandler(IRepositoryWrapper repositoryWrapper) { _repositoryWrapper = repositoryWrapper; } public async Task Handle(DeleteComplexUserCommand request, CancellationToken cancellationToken) { try { await _repositoryWrapper.BeginTransaction(cancellationToken); var complexUser = await _repositoryWrapper.SetRepository() .TableNoTracking .FirstOrDefaultAsync(c => c.ComplexId == request.ComplexId && c.UserId == request.UserId, cancellationToken); if (complexUser == null) throw new AppException("ComplexUser not found", ApiResultStatusCode.NotFound); var complexUserRoles = await _repositoryWrapper.SetRepository().TableNoTracking .Where(c => c.ComplexUserId == complexUser.Id) .ToListAsync(cancellationToken); foreach (var complexUserRole in complexUserRoles) _repositoryWrapper.SetRepository().HardDelete(complexUserRole); await _repositoryWrapper.SaveChangesAsync(cancellationToken); _repositoryWrapper.SetRepository().HardDelete(complexUser); await _repositoryWrapper.SaveChangesAsync(cancellationToken); await _repositoryWrapper.CommitAsync(cancellationToken); return true; } catch (Exception) { await _repositoryWrapper.RollBackAsync(cancellationToken); throw; } } }