<?php

namespace Myvetshop\Module\Clinique\Cart\Preventer;

use Myvetshop\Module\Clinique\Repository\MyvetshopCliniqueRepository;
use Myvetshop\Module\Clinique\Stock\CentravetStockApiFactory;

class CentravetPreventer implements AddToCartPreventerInterface
{
    public const ERROR_MESSAGE = "Le produit que vous souhaitez commander n'est plus disponible. Actualisez la page pour mettre à jour la disponibilité.";

    protected CentravetStockApiFactory $centravetStockApiFactory;

    protected \Db $db;

    protected MyvetshopCliniqueRepository $cliniqueRepository;

    public function __construct(
        CentravetStockApiFactory $centravetStockApiFactory,
        \Db $db,
        MyvetshopCliniqueRepository $cliniqueRepository
    ) {
        $this->centravetStockApiFactory = $centravetStockApiFactory;
        $this->db = $db;
        $this->cliniqueRepository = $cliniqueRepository;
    }

    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);
        $api = $this->centravetStockApiFactory->create();

        if (
            !$api
            || !$clinique
            || 'centravet' !== $clinique->centrale
            || !$clinique->codeClient
        ) {
            return null;
        }

        $reference = $this->db->getValue(
            'SELECT `product_supplier_reference`'
            . ' FROM `' . _DB_PREFIX_ . 'product_supplier`'
            . ' WHERE id_product = ' . (int) $product->id
            . ' AND `id_product_attribute` = ' . $idProductAttribute
            . ' AND `id_supplier` = 1'
        );

        try {
            if (!$api->checkStock($clinique->codeClient, (string) $reference, $qty)) {
                return self::ERROR_MESSAGE;
            }
        } catch (\Exception $e) {
            /*
             *  TODO : Log error
            \Logger::addLog(
                $e->getMessage(),
                1,
                $e->getCode(),
                CentravetStockApi::class,
                null,
                true
            );
            */
        }

        return null;
    }
}
