using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserOrderCQ.Commands.UpdateUserOrder;
public class UpdateUserOrderCommandHandler : IRequestHandler<UpdateUserOrderCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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