<?php

namespace FiloBlu\Refilo\Model;

use FiloBlu\Refilo\Api\CartManagementInterface;
use Magento\Authorization\Model\UserContextInterface;
use Magento\Framework\Exception\AuthorizationException;

class CartManagement implements CartManagementInterface
{
    /**
     * @var \Magento\Quote\Api\GuestCartRepositoryInterface
     */
    private $guestCartRepository;
    /**
     * @var \Magento\Quote\Api\CartRepositoryInterface
     */
    private $cartRepository;
    /**
     * @var UserContextInterface
     */
    private $userContext;

    public function __construct(
        \Magento\Quote\Api\GuestCartRepositoryInterface $guestCartRepository,
        \Magento\Quote\Api\CartRepositoryInterface $cartRepository,
        UserContextInterface $userContext
    ){
        $this->guestCartRepository = $guestCartRepository;
        $this->cartRepository = $cartRepository;
        $this->userContext = $userContext;
    }

    /**
     * @param string $cartId
     * @return true
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function emptyGuestCart(string $cartId){
        $cart = $this->guestCartRepository->get($cartId);
        $cart->removeAllItems();
        $this->cartRepository->save($cart);
        return true;
    }

    /**
     * @param int $cartId
     * @return true
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function emptyCart(int $cartId)
    {
        if ($this->userContext->getUserType() !== UserContextInterface::USER_TYPE_INTEGRATION) {
            throw new AuthorizationException(__('You are not allowed to access this cart.'));
        }
        
        $cart = $this->cartRepository->get($cartId);
        $cart->removeAllItems();
        $this->cartRepository->save($cart);
        return true;
    }
}
