using AutoMapper; using Liber_Incantamentum.Application.DTOs.Mage; using Liber_Incantamentum.Application.Exceptions; using Liber_Incantamentum.Application.Interfaces; using Liber_Incantamentum.Domain.Entities; using Liber_Incantamentum.Domain.Filter; using Liber_Incantamentum.Domain.Repositories; namespace Liber_Incantamentum.Application.Services.Generals { public class MageService : IMageService { private readonly IMageRepository _mageRepository; private readonly IMapper _mapper; public MageService(IMageRepository mageRepository, IMapper mapper) { _mageRepository = mageRepository; _mapper = mapper; } public async Task AddMageAsync(MageDtoCreate dto) { if (dto == null) { throw new ArgumentNullException("The DTO received is null"); } var alreadyExistingMage = await GetAllMagesAsync(new MageDtoFilter { Name = dto.Name, Rank = dto.Rank, Specialisation = dto.Specialisation }); if (alreadyExistingMage.Any()) { throw new AlreadyExistingException("This mage does already exists"); } return await _mageRepository.AddMageAsync(_mapper.Map(dto)); } public async Task DeleteMageAsync(Guid id) { if (id == Guid.Empty) { throw new ArgumentNullException("The id is null"); } var alreadyExistingMage = await GetAllMagesAsync(new MageDtoFilter { Id = id }); if (!alreadyExistingMage.Any()) { throw new NotFoundException("This mage does not exists"); } return await _mageRepository.DeleteMageAsync(id); } public async Task> GetAllMagesAsync(MageDtoFilter filter) { var entities = await _mageRepository.GetAllMagesAsync(_mapper.Map(filter)); return _mapper.Map>(entities); } public async Task? GetMageByIdAsync(Guid id) { if (id == Guid.Empty) { throw new ArgumentNullException("The id is null"); } var alreadyExistingMage = await GetAllMagesAsync(new MageDtoFilter { Id = id }); if (!alreadyExistingMage.Any()) { throw new NotFoundException("This mage does not exists"); } var mage = await _mageRepository.GetMageByIdAsync(id); return _mapper.Map(mage); } public async Task UpdateMageAsync(MageDtoUpdate dto, Guid id) { if (dto == null) { throw new ArgumentNullException("The DTO received is null"); } var alreadyExistingMage = await GetMageByIdAsync(id); if (alreadyExistingMage == null) { throw new NotFoundException("This mage does not exists"); } return await _mageRepository.UpdateMageAsync(_mapper.Map(dto)); } } }