<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Asset\Filter;

use InPost\International\PrestaShop\VersionRange;
use PrestaShop\PrestaShop\Core\ConfigurationInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class FrontCompatibilityFilter implements AssetOptionsFilterInterface
{
    /**
     * @var ConfigurationInterface
     */
    private $configuration;

    /**
     * @var string
     */
    private $psVersion;

    /**
     * @var VersionRange|null
     */
    private static $versionRange;

    public function __construct(ConfigurationInterface $configuration, string $psVersion = _PS_VERSION_)
    {
        $this->configuration = $configuration;
        $this->psVersion = $psVersion;
    }

    /**
     * @internal
     */
    public static function getVersionRange(): VersionRange
    {
        return self::$versionRange ?? self::$versionRange = new VersionRange('8.0.0', '8.1.7');
    }

    /**
     * {@inheritDoc}
     */
    public function filterJavaScriptOptions(array $options): array
    {
        return $this->filterVersion($options, 'PS_JS_THEME_CACHE');
    }

    /**
     * {@inheritDoc}
     */
    public function filterStyleSheetOptions(array $options): array
    {
        return $this->filterVersion($options, 'PS_CSS_THEME_CACHE');
    }

    /**
     * @see https://github.com/PrestaShop/PrestaShop/issues/35341
     */
    private function filterVersion(array $options, string $cacheConfigKey): array
    {
        if (!isset($options['version'])) {
            return $options;
        }

        if (!self::getVersionRange()->contains($this->psVersion)) {
            return $options;
        }

        if (!$this->configuration->get($cacheConfigKey)) {
            return $options;
        }

        unset($options['version']);

        return $options;
    }
}
