2025-08-09 18:09:17 +02:00

84 lines
3.3 KiB
C#

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<bool> AddSpellAsync(SpellDtoCreate dto)
{
if (dto == null)
{
throw new ArgumentNullException("The DTO received is null");
}
var alreadyExistingSpell = await GetAllSpellAsync(new SpellDtoFilter { Name = dto.Name, Description = dto.Description, Type = dto.Type, CreationDate = dto.CreationDate, MageId = dto.MageId });
if (alreadyExistingSpell.Any())
{
throw new AlreadyExistingException("This mage does already exists");
}
return await _spellRepository.AddSpellAsync(_mapper.Map<Spell>(dto));
}
public async Task<bool> DeleteSpellAsync(Guid id)
{
if (id == Guid.Empty)
{
throw new ArgumentNullException("The id is null");
}
var alreadyExistingSpell = await GetAllSpellAsync(new SpellDtoFilter { Id = id });
if (!alreadyExistingSpell.Any())
{
throw new AlreadyExistingException("This mage does not exists");
}
return await _spellRepository.DeleteSpellAsync(id);
}
public async Task<ICollection<SpellDto>> GetAllSpellAsync(SpellDtoFilter filter)
{
var entities = await _spellRepository.GetAllSpellAsync(_mapper.Map<SpellFilter>(filter));
return _mapper.Map<ICollection<SpellDto>>(entities);
}
public async Task<SpellDto>? GetSpellByIdAsync(Guid id)
{
if (id == Guid.Empty)
{
throw new ArgumentNullException("The id is null");
}
var alreadyExistingMage = await GetAllSpellAsync(new SpellDtoFilter { Id = id });
if (!alreadyExistingMage.Any())
{
throw new NotFoundException("This mage does not exists");
}
var mage = await _spellRepository.GetSpellByIdAsync(id);
return _mapper.Map<SpellDto>(mage);
}
public async Task<bool> UpdateSpellAsync(SpellDtoUpdate dto)
{
if (dto == null)
{
throw new ArgumentNullException("The DTO received is null");
}
var alreadyExistingSpell = await GetAllSpellAsync(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 mage does not exists");
}
return await _spellRepository.UpdateSpellAsync(_mapper.Map<Spell>(dto));
}
}
}