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

use InPost\International\DependencyInjection\Compiler\ProvideServiceLocatorFactoriesPass;
use InPost\International\PrestaShop\CommandBus\CommandBusFactory;
use PrestaShop\PrestaShop\Core\CommandBus\CommandBusInterface;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ServiceLocator;

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

assert(isset($container) && $container instanceof ContainerBuilder);

$busFactory = $container->register(CommandBusInterface::class)
    ->setFactory([CommandBusFactory::class, 'create'])
    ->setPublic(false);

if (Tools::version_compare(_PS_VERSION_, '8.0.0')) {
    $container->addCompilerPass(new ProvideServiceLocatorFactoriesPass('inpost.intl.service_locator'));

    $container->register('inpost.intl.command_bus.handler_locator', ServiceLocator::class)
        ->setPublic(false)
        ->addTag('inpost.intl.service_locator', [
            'tag' => 'tactician.handler',
            'index_by' => 'command',
        ]);

    $busFactory->setArgument(0, new Reference('inpost.intl.command_bus.handler_locator'));
} else {
    $busFactory->setArgument(0, new ServiceLocatorArgument(new TaggedIteratorArgument(
        'tactician.handler',
        'command',
        null,
        true
    )));
}
