using Diligent.WebAPI.Business.Extensions; namespace Diligent.WebAPI.Business.Services { public class AdService : IAdService { private readonly DatabaseContext _context; private readonly IMapper _mapper; private readonly ITechnologyService _technologyService; public AdService(DatabaseContext context, IMapper mapper, ITechnologyService technologyService) { _context = context; _mapper = mapper; _technologyService = technologyService; } public async Task> GetAllAsync() { var today = DateTime.Now; return _mapper.Map>(await _context.Ads.Include(x => x.Technologies).Where(x => x.ExpiredAt > today).ToListAsync()); } public async Task GetByIdAsync(int id) { var ad = await _context.Ads.FindAsync(id); if(ad is null) throw new EntityNotFoundException("Ad not found"); return _mapper.Map(ad); } public async Task GetAdDetailsByIdAsync(int id) { var ad = await _context.Ads.Include(x => x.Applicants).Where(x => x.Id == id).FirstOrDefaultAsync(); if (ad is null) throw new EntityNotFoundException("Ad not found"); return _mapper.Map(ad); } public async Task> GetArchiveAds() { var today = DateTime.Now; var archiveAds = await _context.Ads.Where(x => x.ExpiredAt < today).ToListAsync(); return _mapper.Map>(archiveAds); } public async Task> GetFilteredAdsAsync(AdFilterDto filters) { var filteredAds = await _context.Ads.Include(x => x.Technologies).ToListAsync(); return _mapper.Map>(filteredAds.Filter(filters)); } public async Task CreateAsync(AdCreateDto adCreateDto) { var ad = _mapper.Map(adCreateDto); for (int i = 0; i < adCreateDto.TechnologiesIds.Count; i++) { var technology = await _technologyService.GetEntityByIdAsync(adCreateDto.TechnologiesIds[i]); ad.Technologies.Add(technology); } await _context.Ads.AddAsync(ad); await _context.SaveChangesAsync(); } public async Task UpdateAsync(int id, AdUpdateDto adUpdateDto) { var ad = await _context.Ads.FindAsync(id); if (ad is null) throw new EntityNotFoundException("Ad not found"); _mapper.Map(adUpdateDto, ad); _context.Entry(ad).State = EntityState.Modified; await _context.SaveChangesAsync(); } public async Task DeleteAsync(int id) { var ad = await _context.Ads.FindAsync(id); if (ad is null) throw new EntityNotFoundException("Ad not found"); _context.Ads.Remove(ad); await _context.SaveChangesAsync(); } } }