using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.ProductImagesCQ.Commands.DeleteProductImages;
public class DeleteProductImagesCommandHandler : IRequestHandler<DeleteProductImagesCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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