<?php

namespace apexl\Io\modules\system\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\includes\Routes;
use apexl\Io\includes\System;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class globalSystemInfo extends Controller
{
    /** @var Routes */
    protected $route;

    public function __construct()
    {
        parent::__construct();
        $this->route = Routes::getInstance();
    }

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

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

        return System::asJson($response, $routes);
    }
}
