<?php

namespace WordpressModels\DependencyInjection\RestRouteAttributes;

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

class RestRouteCompilerPass implements 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']);

                // ensure the scope is to the current service class
                if ($tag['$scope'] !== $id && class_exists($id)) {
                    $tag['$scope'] = $id;
                }

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