<?php declare(strict_types=1);
/**
 * @author Ryan Spaeth <rspaeth@spaethtech.com>
 * @copyright 2025 - Spaeth Technologies, Archous Networks
 */

namespace SpaethTech\UCRM\SDK\Middleware;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;

class QueryRoutingMiddleware implements MiddlewareInterface
{
    public function __construct(
        protected string $fallback = "/",
        protected array $rewrites = []
    )
    {
    }

    public function process(Request $request, RequestHandler $handler): Response
    {
        $uri = $request->getUri();

        $route = $this->fallback;
        $query = [];

        foreach($request->getQueryParams() as $key => $value)
        {
            if (str_starts_with($key, "/") && $value === "")
            {
                $route = $key;
                continue;
            }

            if ($key === "route" && str_starts_with($value, "/"))
            {
                $route = $value;
                continue;
            }

            $query[$key] = $value;
        }

        foreach($this->rewrites as $from => $to)
        {
            $route = preg_replace($from, $to, $route);
        }

        $uri = $uri
            ->withPath($route)
            ->withQuery($query ? "?".http_build_query($query) : "");

        $request = $request
            ->withUri($uri);

        // Pass the modified request to the next middleware.
        return $handler->handle($request);
    }
}