using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.ProductImagesCQ.Commands.UpdateProductImages;
public class UpdateProductImagesCommandHandler : IRequestHandler<UpdateProductImagesCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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