<?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 Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class SearchableServicesCompilerPass implements CompilerPassInterface
{
    /**
     * (non-PHPdoc).
     *
     * @see \Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface::process()
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('chill_main.search_provider')) {
            throw new \LogicException('service chill_main.search_provider is not defined.');
        }

        $definition = $container->getDefinition(
            'chill_main.search_provider'
        );

        $taggedServices = $container->findTaggedServiceIds(
            'chill.search'
        );

        $knownAliases = [];

        foreach ($taggedServices as $id => $tagAttributes) {
            foreach ($tagAttributes as $attributes) {
                if (!isset($attributes['alias'])) {
                    throw new \LogicException("the 'name' attribute is missing in your service '{$id}' definition");
                }

                if (array_search($attributes['alias'], $knownAliases, true)) {
                    throw new \LogicException('There is already a chill.search service with alias '.$attributes['alias'].'. Choose another alias.');
                }
                $knownAliases[] = $attributes['alias'];

                $definition->addMethodCall(
                    'addSearchService',
                    [new Reference($id), $attributes['alias']]
                );
            }
        }
    }
}
