<?php
declare(strict_types=1);
namespace Helpers;

final class Router
{
    private array $routes = [];

    public function get(string $path, array $handler): void { $this->add('GET', $path, $handler); }
    public function post(string $path, array $handler): void { $this->add('POST', $path, $handler); }
    public function put(string $path, array $handler): void { $this->add('PUT', $path, $handler); }
    public function patch(string $path, array $handler): void { $this->add('PATCH', $path, $handler); }
    public function delete(string $path, array $handler): void { $this->add('DELETE', $path, $handler); }

    private function add(string $method, string $path, array $handler): void
    {
        $pattern = preg_replace('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', '(?P<$1>[^/]+)', '/' . trim($path, '/'));
        $this->routes[] = compact('method', 'pattern', 'handler');
    }

    public function dispatch(string $method, string $path): never
    {
        error_log('Dispatching: ' . $method . ' ' . $path);
    foreach ($this->routes as $route) {
        error_log('Checking: ' . $route['method'] . ' ' . $route['pattern']);
            if ($route['method'] !== $method) continue;
            if (preg_match('#^' . $route['pattern'] . '$#', $path, $matches)) {
                $params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
                [$class, $action] = $route['handler'];
                $controller = new $class();
                $controller->$action(...array_values($params));
                exit();
            }
        }
        Response::error('API route not found', 404);
    }
}
