namespace Brizco.Repository.Handlers.Complexes;

public class DeleteComplexUserCommandHandler : IRequestHandler<DeleteComplexUserCommand, bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public DeleteComplexUserCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }

    public async Task<bool> Handle(DeleteComplexUserCommand request, CancellationToken cancellationToken)
    {
        try
        {
            await _repositoryWrapper.BeginTransaction(cancellationToken);
            var complexUser = await _repositoryWrapper.SetRepository<ComplexUser>()
                .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<ComplexUserRole>().TableNoTracking
                .Where(c => c.ComplexUserId == complexUser.Id)
                .ToListAsync(cancellationToken);
            foreach (var complexUserRole in complexUserRoles)
                _repositoryWrapper.SetRepository<ComplexUserRole>().HardDelete(complexUserRole);
            await _repositoryWrapper.SaveChangesAsync(cancellationToken);

            _repositoryWrapper.SetRepository<ComplexUser>().HardDelete(complexUser);
            await _repositoryWrapper.SaveChangesAsync(cancellationToken);
            await _repositoryWrapper.CommitAsync(cancellationToken);
            return true;
        }
        catch (Exception)
        {
            await _repositoryWrapper.RollBackAsync(cancellationToken);
            throw;
        }
    }
}