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

use Symfony\Component\Asset\Context\ContextInterface;
use Symfony\Component\Asset\PackageInterface;
use Symfony\Component\Asset\PathPackage;
use Symfony\Component\Asset\VersionStrategy\StaticVersionStrategy;
use Symfony\Component\Asset\VersionStrategy\VersionStrategyInterface;

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

abstract class AbstractAssetManager implements AssetManagerInterface
{
    /**
     * @var \Module
     */
    protected $module;

    /**
     * @var ContextInterface|null
     */
    private $context;

    /**
     * @var VersionStrategyInterface|null
     */
    private $versionStrategy;

    /**
     * @var PathPackage|null
     */
    private $package;

    public function __construct(\Module $module, ContextInterface $context = null, VersionStrategyInterface $versionStrategy = null)
    {
        $this->module = $module;
        $this->context = $context;
        $this->versionStrategy = $versionStrategy;
    }

    final public function registerAssets(Assets $assets): void
    {
        foreach ($assets->getJavaScripts() as $path => $options) {
            $this->registerJavaScript($path, $options);
        }

        foreach ($assets->getStyleSheets() as $path => $options) {
            $this->registerStyleSheet($path, $options);
        }

        $this->registerJavaScriptVariables($assets->getJavaScriptVariables());
    }

    /**
     * @return PathPackage
     */
    public function getPackage(): PackageInterface
    {
        return $this->package ?? ($this->package = $this->createPackage());
    }

    abstract protected function getBasePath(): string;

    /**
     * @param array<string, mixed> $options
     */
    abstract protected function registerJavaScript(string $path, array $options = []);

    /**
     * @param array<string, mixed> $options
     */
    abstract protected function registerStyleSheet(string $path, array $options = []);

    protected function registerJavaScriptVariables(array $variables): void
    {
        \Media::addJsDef($variables);
    }

    private function createPackage(): PathPackage
    {
        $basePath = $this->getBasePath();
        $versionStrategy = $this->getVersionStrategy();

        return new PathPackage($basePath, $versionStrategy, $this->context);
    }

    private function getVersionStrategy(): VersionStrategyInterface
    {
        return $this->versionStrategy ?? ($this->versionStrategy = new StaticVersionStrategy($this->module->version, '%s?v=%s'));
    }
}
