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

use InPost\International\Asset\AssetManagerInterface;
use InPost\International\Asset\Event\AdminControllerAssetsRegisteredEvent;
use InPost\International\Asset\Provider\AssetsProviderInterface;
use InPost\International\Asset\Provider\GeoWidgetAssetsProvider;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

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

final class RegisterGeoWidgetAssetsListener implements EventSubscriberInterface
{
    /**
     * @var AssetManagerInterface
     */
    private $assetManager;

    /**
     * @var AssetsProviderInterface
     */
    private $provider;

    /**
     * @param GeoWidgetAssetsProvider $provider
     */
    public function __construct(AssetManagerInterface $assetManager, AssetsProviderInterface $provider)
    {
        $this->assetManager = $assetManager;
        $this->provider = $provider;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            AdminControllerAssetsRegisteredEvent::NAME => 'onAssetsRegistered',
        ];
    }

    public function onAssetsRegistered(AdminControllerAssetsRegisteredEvent $event): void
    {
        if (null === $request = $event->getRequest()) {
            return;
        }

        $route = $request->attributes->get('_route');

        if (!in_array($route, ['admin_orders_view', 'admin_inpost_intl_orders_create_shipment'], true)) {
            return;
        }

        $assets = $this->provider->getAssets();
        $this->assetManager->registerAssets($assets);
    }
}
