<?php

namespace Myvetshop\Module\Clinique\Cart\Preventer;

use Myvetshop\Module\Clinique\Entity\BuyLimitedNumberOfProducts;
use Myvetshop\Module\Clinique\Repository\BuyLimitedNumberOfProductsRepository;

class LimitedNumberOfProductPreventer implements AddToCartPreventerInterface
{
    protected BuyLimitedNumberOfProductsRepository $buyLimitedNumberOfProductsRepository;

    public function __construct(
        BuyLimitedNumberOfProductsRepository $buyLimitedNumberOfProductsRepository
    ) {
        $this->buyLimitedNumberOfProductsRepository = $buyLimitedNumberOfProductsRepository;
    }

    public function getErrorMessage(
        \Product $product,
        int $idProductAttribute,
        int $qty,
        string $operation,
        \Customer $customer,
        \Cart $cart
    ): ?string {
        if ($operation !== 'up') {
            return null;
        }

        /** @var BuyLimitedNumberOfProducts|null $limit */
        $limit = $this->buyLimitedNumberOfProductsRepository->findOneBy(['idProduct' => (int) $product->id]);

        if (!$limit) {
            return null;
        }

        // @phpstan-ignore-next-line
        $productInCart = $cart->getProducts(false, (int) $product->id)[0];
        $productQuantityInCart = (int) $productInCart['cart_quantity'];

        if (($productQuantityInCart + $qty) > $limit->maxQuantity) {
            return 'Impossible d’ajouter cette référence dans votre panier.';
        }

        return null;
    }
}
