<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\DependencyInjection\Compiler;

use Ferienpass\AdminBundle\Section\SectionComponentInterface;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Populates per-scope section_component locators.
 *
 * Each scope (offer, edition, …) gets its own `…locator.<scope>` definition;
 * the legacy `…locator` alias points at the offer scope so existing callers
 * keep working.
 */
class SectionComponentPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container): void
    {
        $byScope = [];
        foreach ($container->findTaggedServiceIds('ferienpass.admin.section_component') as $id => $tags) {
            $definition = $container->getDefinition($id);
            $class = $container->getParameterBag()->resolveValue($definition->getClass() ?? $id);

            if (!class_exists($class) || !is_subclass_of($class, SectionComponentInterface::class)) {
                continue;
            }

            $scope = $class::getSectionScope();
            $sectionName = $class::getSectionName();
            $byScope[$scope][$sectionName] = new Reference($id);
        }

        foreach ($byScope as $scope => $map) {
            $serviceId = \sprintf('ferienpass.admin.section_component_locator.%s', $scope);
            if (!$container->hasDefinition($serviceId)) {
                continue;
            }

            $container->getDefinition($serviceId)->setArgument(0, $map);
        }
    }
}
