<?php

declare(strict_types=1);

namespace App\Core;

final class Router
{
    /** @var array<string, array<string, callable>> */
    private array $routes = [];

    public function get(string $pattern, callable $handler): void
    {
        $this->routes['GET'][$pattern] = $handler;
    }

    public function post(string $pattern, callable $handler): void
    {
        $this->routes['POST'][$pattern] = $handler;
    }

    public function dispatch(Request $request): void
    {
        foreach ($this->routes[$request->method] ?? [] as $pattern => $handler) {
            $regex = '#^' . preg_replace('#\{(\w+)\}#', '(?P<$1>[^/]+)', $pattern) . '$#';
            if (preg_match($regex, $request->path, $m)) {
                $params = array_filter($m, 'is_string', ARRAY_FILTER_USE_KEY);
                // Percent-decode params so e.g. a page slug containing spaces
                // ("My%20Page") still matches its database value.
                $params = array_map('rawurldecode', $params);
                $handler($request, $params);
                return;
            }
        }

        if (str_starts_with($request->path, '/api')) {
            Response::error('Not found', 404);
        }
        http_response_code(404);
        echo '404 Not Found';
    }
}
