<?php

namespace App\Framework\Router;

use App\Framework\Core\Route;

final readonly class CompiledRoutes
{
    /**
     * @param array<string, array<string, Route>> $staticRoutes
     * @param array<string, CompiledPattern|null> $dynamicPatterns
     */
    public function __construct(
        private array $staticRoutes,
        private array $dynamicPatterns,
        private array $namedRoutes,
    ) {}

    public function getStaticRoute(string $method, string $path): ?Route
    {
        return $this->staticRoutes[$method][$path] ?? null;
    }

    public function getCompiledPattern(string $method): ?CompiledPattern
    {
        return $this->dynamicPatterns[$method] ?? null;
    }

    public function getNamedRoute(string $name): ?Route
    {
        return $this->namedRoutes[$name] ?? null;
    }

    public function hasNamedRoute(string $name): bool
    {
        return isset($this->namedRoutes[$name]);
    }

    public function getAllNamedRoutes(): array
    {
        return $this->namedRoutes;
    }

    public function generateUrl(string $name, array $params = []): ?string
    {
        $route = $this->getNamedRoute($name);
        if(!$route) {
            return null;
        }
        return $this->buildUrlFromRoute($route, $params);
    }


    public function getStats(): array
    {
        $staticCount = array_sum(array_map('count', $this->staticRoutes));
        $dynamicCount = count(array_filter($this->dynamicPatterns));
        $namedCount = count($this->namedRoutes);

        return [
            'static_routes' => $staticCount,
            'dynamic_patterns' => $dynamicCount,
            'named_routes' => $namedCount,
            'total_methods' => count($this->staticRoutes)
        ];
    }

    private function buildUrlFromRoute(Route $route, array $params): string
    {
        $path = $route->path;

        foreach ($params as $key => $value) {
            $path = str_replace("{{$key}}", (string)$value, $path);
        }
        return $path;
    }
}
