using AutoMapper; using Liber_Incantamentum.Application.DTOs.Spell; 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 SpellService : ISpellService { private readonly ISpellRepository _spellRepository; private readonly IMapper _mapper; public SpellService(ISpellRepository spellRepository, IMapper mapper) { _spellRepository = spellRepository; _mapper = mapper; } public async Task AddSpellAsync(SpellDtoCreate dto) { if (dto == null) { throw new ArgumentNullException("The DTO received is null"); } var alreadyExistingSpell = await GetAllSpellsAsync(new SpellDtoFilter { Name = dto.Name, Description = dto.Description, Type = dto.Type, CreationDate = dto.CreationDate, MageId = dto.MageId }); if (alreadyExistingSpell.Any()) { throw new AlreadyExistingException("This spell does already exists"); } return await _spellRepository.AddSpellAsync(_mapper.Map(dto)); } public async Task DeleteSpellAsync(Guid id) { if (id == Guid.Empty) { throw new ArgumentNullException("The id is null"); } var alreadyExistingSpell = await GetAllSpellsAsync(new SpellDtoFilter { Id = id }); if (!alreadyExistingSpell.Any()) { throw new AlreadyExistingException("This spell does not exists"); } return await _spellRepository.DeleteSpellAsync(id); } public async Task> GetAllSpellsAsync(SpellDtoFilter filter) { var entities = await _spellRepository.GetAllSpellsAsync(_mapper.Map(filter)); return _mapper.Map>(entities); } public async Task? GetSpellByIdAsync(Guid id) { if (id == Guid.Empty) { throw new ArgumentNullException("The id is null"); } var alreadyExistingMage = await GetAllSpellsAsync(new SpellDtoFilter { Id = id }); if (!alreadyExistingMage.Any()) { throw new NotFoundException("This spell does not exists"); } var mage = await _spellRepository.GetSpellByIdAsync(id); return _mapper.Map(mage); } public async Task UpdateSpellAsync(SpellDtoUpdate dto, Guid i) { if (dto == null) { throw new ArgumentNullException("The DTO received is null"); } var alreadyExistingSpell = await GetAllSpellsAsync(new SpellDtoFilter { Id = dto.Id, Name = dto.Name, Description = dto.Description, Type = dto.Type, CreationDate = dto.CreationDate, MageId = dto.MageId }); if (!alreadyExistingSpell.Any()) { throw new NotFoundException("This spell does not exists"); } return await _spellRepository.UpdateSpellAsync(_mapper.Map(dto)); } } }