using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.ProductGalleriesCQ.Commands.UpdateProductGalleries;
public class UpdateProductGallerysCommandHandler : IRequestHandler<UpdateProductGalleriesCommand, Unit>
{
    private readonly IApplicationDbContext _context;

    public UpdateProductGallerysCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<Unit> Handle(UpdateProductGalleriesCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.ProductGalleries
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken) ?? throw new NotFoundException(nameof(ProductGallery), request.Id);
        request.Adapt(entity);
        _context.ProductGalleries.Update(entity);
        entity.AddDomainEvent(new UpdateProductGallerysEvent(entity));
        await _context.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}
