<?php

namespace Myvetshop\Module\Clinique\Cart\Preventer;

use Myvetshop\Module\Clinique\Repository\MyvetshopCliniqueRepository;

class BlockedProductPreventer implements AddToCartPreventerInterface
{
    protected MyvetshopCliniqueRepository $cliniqueRepository;

    protected string $defaultMessage;

    public function __construct(
        MyvetshopCliniqueRepository $cliniqueRepository,
        string $defaultMessage
    ) {
        $this->cliniqueRepository = $cliniqueRepository;
        $this->defaultMessage = $defaultMessage;
    }

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

        $clinique = $this->cliniqueRepository->findByGroupId((int) $customer->id_default_group);

        if (!$clinique) {
            return null;
        }

        $productIds = \array_map(
            'intval',
            \explode(',', $clinique->blockedProducts ?: ''),
        );

        if (\in_array((int) $product->id, $productIds)) {
            return $clinique->blockedProductsMessage ?: $this->defaultMessage;
        }

        return null;
    }
}
