namespace NetinaShop.Core.EntityServices.OrderBagHandlers;

public class RemoveFromOrderBagCommandHandler : IRequestHandler<RemoveFromOrderBagCommand, OrderSDto>
{
    private readonly ICurrentUserService _currentUserService;
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly IMediator _mediator;

    public RemoveFromOrderBagCommandHandler(ICurrentUserService currentUserService, IRepositoryWrapper repositoryWrapper,IMediator mediator)
    {
        _currentUserService = currentUserService;
        _repositoryWrapper = repositoryWrapper;
        _mediator = mediator;
    }
    public async Task<OrderSDto> Handle(RemoveFromOrderBagCommand request, CancellationToken cancellationToken)
    {
        if (_currentUserService.UserId == null)
            throw new AppException("User id notfound", ApiResultStatusCode.BadRequest);
        if (!Guid.TryParse(_currentUserService.UserId, out Guid userId))
            throw new AppException("User id wrong", ApiResultStatusCode.BadRequest);

        var orderBag = await _mediator.Send(new GetUserOrderBagQuery(), cancellationToken);

        foreach (var requestDto in request.RequestDtos)
        {
            var product = await _repositoryWrapper.SetRepository<Product>()
                .TableNoTracking
                .FirstOrDefaultAsync(p => p.Id == requestDto.ProductId, cancellationToken);

            if (product == null)
                throw new AppException("Product not found ", ApiResultStatusCode.NotFound);
            if (!product.IsEnable)
                throw new AppException("Product is not enable", ApiResultStatusCode.BadRequest);


            orderBag.RemoveFromOrderBag(product.Id, requestDto.Count);
        }


        _repositoryWrapper.SetRepository<Order>().Update(orderBag);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        var order = await _mediator.Send(new CalculateOrderCommand(orderBag.Id), cancellationToken);

        return order.AdaptToSDto();
    }
}