<?php

declare(strict_types=1);

namespace apexl\Io\controllers;

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

final readonly class CatchAllController extends Controller
{
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        // Did we throw a true 404? or is there an existing system error?
        if (!$this->output->getSystemErrors()) {
            // No errors? throw the 404, otherwise return the system error code..
            return $this->json($response, [
                'title' => '404 Not Found',
                'code' => 404,
                'message' => 'The requested resource could not be found. Please verify the URI and try again.'
            ], 404);

        }
        // We got at least one system error. return the code for the first one we got.
        $existingErrors = Output::getSystemErrors() ?? [];
        $error = array_shift($existingErrors);

        return $this->json($response, status: $error['status'] ?? 500);
    }
}