<?php

declare(strict_types=1);

namespace SeoScope\Http;

/**
 * Minimal router: matches method + path (no regex) to a handler.
 * Designed to keep WebDispatcher routing declarative and easy to extend.
 */
final class Router
{
    /** @var list<array{method:string,path:string,handler:callable}> */
    private array $routes = [];

    public function add(string $method, string $path, callable $handler): self
    {
        $this->routes[] = [
            'method' => strtoupper($method),
            'path' => $this->normalizePath($path),
            'handler' => $handler,
        ];
        return $this;
    }

    /**
     * @return bool true if matched and executed
     */
    public function dispatch(string $method, string $path): bool
    {
        $method = strtoupper($method);
        $path = $this->normalizePath($path);
        foreach ($this->routes as $r) {
            if ($r['method'] === $method && $r['path'] === $path) {
                ($r['handler'])();
                return true;
            }
        }
        return false;
    }

    private function normalizePath(string $path): string
    {
        $path = '/' . trim($path, '/');
        return $path === '/' ? '/' : $path;
    }
}

