using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.ProductsCQ.Commands.DeleteProducts;
public class DeleteProductsCommandHandler : IRequestHandler<DeleteProductsCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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