<?php

namespace AutoAdmin\Bundle\BrickBuilder\DependencyInjection\Compiler;

use AutoAdmin\Bundle\BrickBuilder\Brick\BrickConfigManager;
use AutoAdmin\Bundle\BrickBuilder\Brick\BrickHandlerManagerInterface;
use AutoAdmin\Bundle\BrickBuilder\Request\CustomRequestStack;
use Exception;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\DependencyInjection\Reference;

class BrickHandlerCompilerPass implements CompilerPassInterface
{
    /**
     * @inheritDoc
     */
    public function process(ContainerBuilder $container): void
    {
        // replace default request stack by ours to add a fake request during cli calls
        $requestStack = $container->getDefinition('request_stack');
        $requestStack->setClass(CustomRequestStack::class);

        $serviceArguments = [];
        $tagged = $container->findTaggedServiceIds('aa_brick.handler');

        foreach ($tagged as $id => $value) {
            $def = $container->getDefinition($id);

            $def->addMethodCall('setTwig', [new Reference('twig')]);
            $def->addMethodCall('setAppEnv', [new Parameter('kernel.environment')]);
            // "configuration" setter is called later

            $tags = $def->getTag('aa_brick.handler');
            foreach ($tags as $tag) {
                $brickType = $tag['brick_type'] ?? $id::BRICK_TYPE ?? null;// brick type

                if (empty($brickType)) {
                    throw new Exception(
                        sprintf(
                            'You must provide a "BRICK_TYPE" constant when tagging a service with aa_brick.handler (%s)',
                            $id
                        )
                    );
                }

                $serviceArguments[$brickType] = new Reference($id);
            }
        }

        $managerDef = $container->getDefinition(BrickHandlerManagerInterface::class);
        $managerDef->setArgument('$handlers', $serviceArguments);
        $managerDef = $container->getDefinition(BrickConfigManager::class);
        $managerDef->setArgument('$handlers', $serviceArguments);
    }
}
