<?php

/**
 * Коллекция маршрутов Flowaxy CMS
 * Управление набором маршрутов
 *
 * @package Flowaxy\Core\Routing
 * @version 1.0.0 Alpha prerelease
 */

declare(strict_types=1);

namespace Flowaxy\Core\Routing;

class RouteCollection
{
    private array $routes = [];
    private array $routesByMethod = [];

    private static ?self $instance = null;

    /**
     * Получить экземпляр (singleton)
     *
     * @return self
     */
    public static function getInstance(): self
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Очистить коллекцию маршрутов (для hot reload)
     *
     * @return void
     */
    public static function clear(): void
    {
        if (self::$instance !== null) {
            self::$instance->routes = [];
            self::$instance->routesByMethod = [];
        }
    }

    public function add(Route $route): void
    {
        $this->routes[] = $route;
        foreach ($route->getMethods() as $method) {
            $this->routesByMethod[$method][] = $route;
        }
    }

    public function getRoutes(): array
    {
        return $this->routes;
    }

    public function getRoutesByMethod(string $method): array
    {
        return $this->routesByMethod[strtoupper($method)] ?? [];
    }

    public function hasRoute(string $method, string $path): bool
    {
        $method = strtoupper($method);
        $normalizedPath = trim($path, '/');
        $methodRoutes = $this->routesByMethod[$method] ?? [];

        foreach ($methodRoutes as $route) {
            if ($route->getPath() === $normalizedPath) {
                return true;
            }
        }

        return false;
    }

    public function findByName(string $name): ?Route
    {
        foreach ($this->routes as $route) {
            if ($route->getName() === $name) {
                return $route;
            }
        }

        return null;
    }

    /**
     * Очистить коллекцию маршрутов (нестатический метод)
     *
     * @return void
     */
    public function clearInstance(): void
    {
        $this->routes = [];
        $this->routesByMethod = [];
    }

    public function count(): int
    {
        return count($this->routes);
    }
}
