using MediatR; using cuqmbr.TravelGuide.Application.Common.Interfaces.Persistence; using cuqmbr.TravelGuide.Domain.Entities; using AutoMapper; using cuqmbr.TravelGuide.Application.Common.Exceptions; namespace cuqmbr.TravelGuide.Application.Regions.Commands.AddRegion; public class AddRegionCommandHandler : IRequestHandler { private readonly UnitOfWork _unitOfWork; private readonly IMapper _mapper; public AddRegionCommandHandler( UnitOfWork unitOfWork, IMapper mapper) { _unitOfWork = unitOfWork; _mapper = mapper; } public async Task Handle( AddRegionCommand request, CancellationToken cancellationToken) { var entity = await _unitOfWork.RegionRepository.GetOneAsync( e => e.Name == request.Name && e.Country.Guid == request.CountryUuid, cancellationToken); if (entity != null) { throw new DuplicateEntityException( "Region with given name already exists."); } var parentEntity = await _unitOfWork.CountryRepository.GetOneAsync( e => e.Guid == request.CountryUuid, cancellationToken); if (parentEntity == null) { throw new NotFoundException( $"Parent entity with Guid: {request.CountryUuid} not found."); } entity = new Region() { Name = request.Name, CountryId = parentEntity.Id }; entity = await _unitOfWork.RegionRepository.AddOneAsync( entity, cancellationToken); await _unitOfWork.SaveAsync(cancellationToken); _unitOfWork.Dispose(); return _mapper.Map(entity); } }