<?php

namespace WordpressModels\DependencyInjection\RestRouteAttributes;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class RestRouteCompilerPass implements \Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (!$container->has(RestRouteRegistry::class)) {
            return;
        }
        $registry = $container->getDefinition(RestRouteRegistry::class);

        $controllerScopes = $container->findTaggedServiceIds('wp_rest_controller_scope');

        foreach ($controllerScopes as $id => $tags) {
            foreach ($tags as $tag) {
                $registry->addMethodCall('addScope', [...$tag]);
            }
        }

        $services = $container->findTaggedServiceIds('wp_rest_controller');

        foreach ($services as $id => $tags) {
            foreach ($tags as $tag) {
                // unset the method
                $method = $tag['$method'];
                unset($tag['$method']);

                $registry->addMethodCall('addRoute', [
                    '$callable' => [new Reference($id), $method],
                    ...$tag
                ]);
            }
        }
    }
}