<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\DependencyInjection\CompilerPass;

use Chill\MainBundle\Routing\MenuComposer;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class MenuCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('chill.main.menu_composer')) {
            throw new \LogicException(sprintf('The service %s does not exists in container.', MenuComposer::class));
        }

        $menuComposerDefinition = $container->getDefinition('chill.main.menu_composer');

        $services = [];

        foreach ($container->findTaggedServiceIds('chill.menu_builder') as $id => $tags) {
            $services[] = [
                'id' => $id,
                'priority' => $tags[0]['priority'] ?? 100,
            ];
        }

        usort($services, static fn ($a, $b) => $a['priority'] <=> $b['priority']);

        foreach ($services as $service) {
            $class = $container->getDefinition($service['id'])->getClass();

            foreach ($class::getMenuIds() as $menuId) {
                $menuComposerDefinition
                    ->addMethodCall('addLocalMenuBuilder', [new Reference($service['id']), $menuId]);
            }
        }
    }
}
