<?php

declare(strict_types=1);

namespace Gls\GlsPoland\DependencyInjection\CompilerPass;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

final class ProvideFactoriesCompilerPass implements CompilerPassInterface
{
    private $container;
    private $factoryId;

    public function __construct(ContainerInterface $container, string $factoryId)
    {
        $this->container = $container;
        $this->factoryId = $factoryId;
    }

    public function process(ContainerBuilder $container): void
    {
        foreach ($container->getDefinitions() as $id => $definition) {
            if (!$definition->isSynthetic() || !$this->container->has($id)) {
                continue;
            }

            $definition
                ->setSynthetic(false)
                ->setFactory([new Reference($this->factoryId), 'get'])
                ->setArguments([$id]);
        }

        $container->addDefinitions([
            $this->factoryId => (new Definition())
                ->setClass(ContainerInterface::class)
                ->setSynthetic(true),
        ]);
    }
}
