2025-08-16 21:01:14 +02:00

73 lines
2.6 KiB
C#

using Liber_Incantamentum.Domain.Entities;
using Liber_Incantamentum.Domain.Filter;
using Liber_Incantamentum.Domain.Repositories;
using Liber_Incantamentum.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Liber_Incantamentum.Application.Exceptions;
namespace Liber_Incantamentum.Infrastructure.Repositories
{
public class SpellRepository : ISpellRepository
{
private readonly AppDbContext _context;
public SpellRepository(AppDbContext context)
{
_context = context;
}
public async Task<bool> AddSpellAsync(Spell entity)
{
await _context.Spells.AddAsync(entity);
return await _context.SaveChangesAsync() > 0;
}
public async Task<bool> DeleteSpellAsync(Guid id)
{
var spell = await GetSpellByIdAsync(id);
_context.Spells.Remove(spell);
return await _context.SaveChangesAsync() > 0;
}
public async Task<ICollection<Spell>> GetAllSpellsAsync(SpellFilter filterEntity)
{
var query = _context.Spells.AsQueryable();
if (filterEntity.Id != Guid.Empty)
query = query.Where(m => m.Id == filterEntity.Id);
if (!string.IsNullOrEmpty(filterEntity.Name))
query = query.Where(m => EF.Functions.ILike(m.Name, filterEntity.Name));
if (!string.IsNullOrEmpty(filterEntity.Description))
query = query.Where(m => EF.Functions.ILike(m.Description, filterEntity.Description));
if (!string.IsNullOrEmpty(filterEntity.Type))
query = query.Where(m => EF.Functions.ILike(m.Type, filterEntity.Type));
if (filterEntity.CreationDate != default)
query = query.Where(m => m.CreationDate == filterEntity.CreationDate);
if (filterEntity.MageId != Guid.Empty)
query = query.Where(m => m.MageId == filterEntity.MageId);
var mages = await query.ToListAsync();
return mages;
}
public async Task<Spell> GetSpellByIdAsync(Guid id)
{
var spell = await _context.Spells.FindAsync(id);
if (spell == null) throw new NotFoundException($"No spell has been found with the id : {id}");
return spell;
}
public async Task<bool> UpdateSpellAsync(Spell entity)
{
var spell = await GetSpellByIdAsync(entity.Id);
_context.Entry(spell).CurrentValues.SetValues(entity);
if (!_context.ChangeTracker.HasChanges()) return false;
return await _context.SaveChangesAsync() > 0;
}
}
}