<?php

declare(strict_types=1);

namespace Core;

class Route
{
    protected string $method;
    protected string $path;
    protected mixed $handler;
    protected array $parameters = [];

    public function __construct(string $method, string $path, mixed $handler)
    {
        $this->method = strtoupper($method);
        $this->path = $path;
        $this->handler = $handler;
    }

    public function matches(string $method, string $path): bool
    {
        if (strtoupper($method) !== $this->method) {
            return false;
        }

        $routePattern = preg_replace('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', '([^/]+)', $this->path);
        $routePattern = '#^' . $routePattern . '$#';

        if (!preg_match($routePattern, $path, $matches)) {
            return false;
        }

        array_shift($matches);
        preg_match_all('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', $this->path, $names);

        $this->parameters = [];

        foreach ($names[1] as $index => $name) {
            $this->parameters[$name] = $matches[$index] ?? null;
        }

        return true;
    }

    public function dispatch(App $app): mixed
    {
        return $app->call($this->handler, $this->parameters);
    }
}
