using CMSMicroservice.Application.UserCartsCQ.Commands.DeleteUserCarts;
using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserCartsCQ.Commands.UpdateUserCarts;
public class UpdateUserCartsCommandHandler : IRequestHandler<UpdateUserCartsCommand, Unit>
{
    private readonly IApplicationDbContext _context;
    private readonly ISender _sender;

    public UpdateUserCartsCommandHandler(IApplicationDbContext context, ISender sender)
    {
        _context = context;
        _sender = sender;
    }

    public async Task<Unit> Handle(UpdateUserCartsCommand request, CancellationToken cancellationToken)
    {
        if (request.Count<=0)
        {
            await _sender.Send(request.Adapt<DeleteUserCartsCommand>(), cancellationToken);
        }
        var entity = await _context.UserCarts
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken) ?? throw new NotFoundException(nameof(UserCart), request.Id);
        request.Adapt(entity);
        _context.UserCarts.Update(entity);
        entity.AddDomainEvent(new UpdateUserCartsEvent(entity));
        await _context.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}
