using Netina.Domain.Entities.Brands; namespace Netina.Repository.Handlers.Brands; public class UpdateBrandCommandHandler(IRepositoryWrapper repositoryWrapper,IMartenRepositoryWrapper martenRepositoryWrapper,IMediator mediator) : IRequestHandler { public async Task Handle(UpdateBrandCommand request, CancellationToken cancellationToken) { var ent = await repositoryWrapper.SetRepository().TableNoTracking .FirstOrDefaultAsync(b => b.Id == request.Id, cancellationToken); if (ent == null) throw new AppException("Brand not found"); var newEnt = Brand.Create(request.PersianName,request.EnglishName, request.Description, request.HasSpecialPage, request.PageUrl); newEnt.Id = ent.Id; newEnt.CreatedAt = ent.CreatedAt; newEnt.CreatedBy = ent.CreatedBy; var dbFiles = await repositoryWrapper.SetRepository().TableNoTracking .Where(s => s.BrandId == newEnt.Id).ToListAsync(cancellationToken); foreach (var dbFile in dbFiles) { if (request.Files.FirstOrDefault(s => s.Id == dbFile.Id) == null) { repositoryWrapper.SetRepository().Delete(dbFile); await repositoryWrapper.SaveChangesAsync(cancellationToken); } } foreach (var file in request.Files.Where(f => f.Id == default)) { newEnt.AddFile(file.Name, file.FileLocation, file.FileName, file.IsHeader, file.IsPrimary, file.FileType); } //Check MetaTags var dbMetaTags = await repositoryWrapper.SetRepository() .TableNoTracking .Where(f => f.BrandId == ent.Id) .ToListAsync(cancellationToken); foreach (var feature in dbMetaTags.Where(feature => request.MetaTags.Any(f => f.Key == feature.Type) == false)) { repositoryWrapper.SetRepository() .Delete(feature); await repositoryWrapper.SaveChangesAsync(cancellationToken); } foreach (var (key, value) in request.MetaTags.Where(f => dbMetaTags.Any(dbf => dbf.Type == f.Key) == false)) newEnt.AddMetaTag(key, value); repositoryWrapper.SetRepository().Update(newEnt); await repositoryWrapper.SaveChangesAsync(cancellationToken); await UpdateFaqAsync(newEnt, request.Faqs, cancellationToken); return true; } private async Task UpdateFaqAsync(Brand newEnt, Dictionary faqs, CancellationToken cancellationToken) { var url = newEnt.GetWebSiteUrl(); var oldFaq = await martenRepositoryWrapper.SetRepository() .GetEntityAsync(f => f.Slug == newEnt.Slug, cancellationToken); var newFaq = await martenRepositoryWrapper.SetRepository() .GetEntityAsync(f => f.Slug == url, cancellationToken); if (oldFaq != null) await mediator.Send(new DeleteFaqCommand(oldFaq.Id), cancellationToken); if (newFaq == null) await mediator.Send(new CreateFaqCommand(faqs, url, newEnt.EnglishName), cancellationToken); else await mediator.Send(new UpdateFaqCommand(newFaq.Id, faqs, url, newEnt.EnglishName), cancellationToken); } }