<?php

declare(strict_types=1);

namespace External\HannahBundle\EventSubscriber;

use External\HannahBundle\SAP\Util\SAPStockUtil;
use KupShop\ContentBundle\View\Exception\ValidationException;
use KupShop\OrderingBundle\Event\CartEvent;
use KupShop\OrderingBundle\Exception\CartValidationException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class CartSubscriber implements EventSubscriberInterface
{
    private SAPStockUtil $stockUtil;

    public function __construct(SAPStockUtil $stockUtil)
    {
        $this->stockUtil = $stockUtil;
    }

    public static function getSubscribedEvents()
    {
        return [
            CartEvent::CHECK_CART => [
                ['checkCartStock', 200],
            ],  CartEvent::CHECK_CART_ITEMS => [
                ['checkCartPrice', 200],
            ],
        ];
    }

    /** Online kontrola skladovosti pred odeslanim objednavky */
    public function checkCartStock(CartEvent $event): void
    {
        try {
            $this->stockUtil->checkCart($event->getCart());
        } catch (ValidationException $e) {
            throw new CartValidationException($e->getMessage());
        }
    }

    /** Kontrola, zda košík nemá nulovou ceny - https://klient.wpj.cz/service/task/15133/change/ */
    public function checkCartPrice(CartEvent $event): void
    {
        $purchaseState = $event->getCart()->getPurchaseState();

        if ($purchaseState->getProducts() && $purchaseState->getActiveCoupons() && !$purchaseState->getTotalPrice()->getPriceWithVat()->isPositive()) {
            throw new CartValidationException(translate('payment_coupon_min_price', 'cart_validation'));
        }
    }
}
