<?php

namespace WordpressModels\DependencyInjection\RestRouteAttributes;

use WordpressModels\DependencyInjection\HookAttributes\Attributes\Action;
use WordpressModels\Rest\Permissions\RequestPermissionEvaluator;

/**
 * Register rest routes with the WordPress rest api.
 */
class RestRouteInitializer
{

    public function __construct(private RestRouteRegistry $registry)
    {
    }

    #[Action('rest_api_init')]
    public function registerRoutes()
    {
        $routes = $this->registry->getRoutes();

        foreach ($routes as $scopeConfig) {
            $baseRoute = $scopeConfig['baseRoute'];
            $override = $scopeConfig['override'];
            $public = $scopeConfig['public'];
            $namespace = $scopeConfig['namespace'];
            $permission = $scopeConfig['permission'];

            foreach ($scopeConfig['routes'] as $route) {
                $permissionCallback = null;

                // check permission exists
                $permission = $permission ?? $route['permission'] ?? null;

                if ($permission) {
                    // if expression is directly callable, use as callback,
                    // else wrap expression in RequestPermissionEvaluator
                    $permissionCallback = is_callable($permission)
                        ? $permission
                        : new RequestPermissionEvaluator($permission);
                }

                register_rest_route(
                    $route['namespace'] ?: $namespace,
                    join('/', array_filter([$baseRoute, $route['route']])),
                    [
                        'methods' => $route['methods'],
                        'callback' => $route['callable'],
                        'permission_callback' => $permissionCallback,
                        'args' => $route['arguments'],
                        'show_in_index' => $route['public'] ?? $public,
                    ],
                    $route['override'] ?? $override
                );
            }
        }
    }

}