using AutoMapper; using RT.Domain.Entities; using RT.Infrastructure.Repositories; namespace RT.Application.Services; public abstract class Service( IRepository repository, IMapper mapper) : IService where TEntity : BaseEntity { protected readonly IRepository Repository = repository; protected readonly IMapper Mapper = mapper; public virtual async Task> GetAllAsync(CancellationToken ct = default) { var entities = await Repository.GetAllAsync(ct); return Mapper.Map>(entities); } public virtual async Task GetByIdAsync(Guid id, CancellationToken ct = default) { var entity = await Repository.GetByIdAsync(id, ct); return entity is null ? default : Mapper.Map(entity); } public virtual async Task CreateAsync(TCreate dto, CancellationToken ct = default) { var entity = Mapper.Map(dto); await Repository.InsertAsync(entity, ct); return Mapper.Map(entity); } public virtual async Task UpdateAsync(Guid id, TUpdate dto, CancellationToken ct = default) { var entity = await Repository.GetByIdAsync(id, ct) ?? throw new KeyNotFoundException($"{typeof(TEntity).Name} {id} not found."); Mapper.Map(dto, entity); await Repository.UpdateAsync(entity, ct); return Mapper.Map(entity); } public virtual async Task DeleteAsync(Guid id, CancellationToken ct = default) { var entity = await Repository.GetByIdAsync(id, ct) ?? throw new KeyNotFoundException($"{typeof(TEntity).Name} {id} not found."); await Repository.RemoveAsync(entity, ct); } }