<?php

namespace Myvetshop\Module\Clinique\Prestashop\Product;

use PrestaShop\PrestaShop\Adapter\LegacyContext;

class ProductPriceComputer
{
    private \Cache $cache;

    private LegacyContext $legacyContext;

    public function __construct(
        \Cache $cache,
        LegacyContext $legacyContext
    ) {
        $this->cache = $cache;
        $this->legacyContext = $legacyContext;
    }

    public function computePrivilegePrice(
        \Combination $combination,
        \Group $group
    ): float {
        // Tous les groupes < 4 ne sont pas des groupes privilège !
        $idDefaultGroup = \max((int) $group->id, 4);

        $context = $this->legacyContext->getContext();
        \assert(null !== $context);

        $tarifPrivilege = \Product::priceCalculation(
            (int) $context->shop->id,
            $combination->id_product,
            (int) $combination->id,
            (int) $context->country->id,
            // @phpstan-ignore-next-line
            null,
            // @phpstan-ignore-next-line
            null,
            $context->currency ? (int) $context->currency->id : 0,
            $idDefaultGroup,
            1,
            $group->price_display_method == PS_TAX_INC,
            2,
            false,
            true,
            true,
            $specificPrice,
            true
        );

        return $tarifPrivilege ?? 0.0;
    }

    /**
     * Wrapper avec cache de ProductPriceComputer::computePrivilegePrice
     *
     * @see computePrivilegePrice
     */
    public function getPrivilegePrice(
        \Combination $combination,
        \Group $group
    ): float {
        $cacheKey = 'Product::computeTarifPrivilege-' . $combination->id_product
            . '-' . $combination->id . '-' . $group->id;

        if ($this->cache->exists($cacheKey)) {
            $tarifPrivilege = $this->cache->get($cacheKey);

            if (!\is_string($tarifPrivilege) && !\is_float($tarifPrivilege) && !\is_int($tarifPrivilege)) {
                $tarifPrivilege = null;
            } else {
                $tarifPrivilege = \floatval($tarifPrivilege);
            }
        } else {
            $tarifPrivilege = null;
        }

        if (null === $tarifPrivilege) {
            $tarifPrivilege = $this->computePrivilegePrice($combination, $group);

            $this->cache->set($cacheKey, $tarifPrivilege, 3600);
        }

        return $tarifPrivilege;
    }
}
