<?php

namespace apexl\Io\modules\system\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\includes\RouteManager;
use apexl\Io\services\Output;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class globalSystemInfo extends Controller
{
    public function __construct(
        protected RouteManager $routeManager,
        Output $output,
    ) {
        parent::__construct($output);
    }

    /**
     * Get all available routes and information attached to them, return as a structured array for JSON response.
     * @method GET
     */
    public function getRoutes(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $routeNames = $this->routeManager->routes;
        $routes = [];
        foreach ($routeNames as $name => $object) {
            $args = $object->getArgs();
            $moduleName = $args['moduleName'] ?? 'Core';
            if (!isset($routes[$moduleName])) {
                $routes[$moduleName] = [];
            }
            $verb = strtolower($object->getMethod()->name);
            $routes[$moduleName][$verb] = $routes[$moduleName][$verb] ?? [];

            $routes[$moduleName][$verb][] = (object) [
                'name' => $name,
                'verb' => $object->getMethod()->name,
                'pattern' => $object->getPattern(),
                'callable' => $object->getCallable(),
                'args' => $object->getArgs(),
            ];
        }

        return $this->json($response, $routes);
    }
}
