using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserOrderCQ.Commands.DeleteUserOrder;
public class DeleteUserOrderCommandHandler : IRequestHandler<DeleteUserOrderCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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