<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Asset;

use Gls\GlsPoland\Configuration\ConfigurationInterface;
use Gls\GlsPoland\PrestaShop\Configuration\Adapter\Configuration;
use Gls\GlsPoland\PrestaShop\VersionRange;

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

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

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

    public static function create(): self
    {
        return new self(new Configuration(), _PS_VERSION_);
    }

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

    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;
        }

        static $versionRange;

        $versionRange = $versionRange ?? new VersionRange('8.0.0', '8.1.7');

        if (!$versionRange->contains($this->psVersion)) {
            return $options;
        }

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

        unset($options['version']);

        return $options;
    }
}
