<?php
declare(strict_types=1);

namespace App\Framework\StaticSite;

use App\Framework\Router\HttpRouter;
use App\Framework\Router\Route;
use App\Framework\Router\RouteCollection;

class RouteCollector
{
    private HttpRouter $router;

    public function __construct(HttpRouter $router)
    {
        $this->router = $router;
    }

    /**
     * Sammelt alle Routen aus dem Router
     *
     * @return array Liste aller Routen-Pfade
     */
    public function collectRoutes(): array
    {
        $routes = [];
        $routeCollection = $this->router->getRoutes();

        if ($routeCollection instanceof RouteCollection) {
            foreach ($routeCollection->getAll() as $route) {
                if ($route instanceof Route) {
                    $path = $route->path;
                    // Nur GET-Routen für statische Seiten verwenden
                    if (in_array('GET', $route->methods)) {
                        $routes[] = $path;
                    }
                }
            }
        }

        return $routes;
    }

    /**
     * Filtert die Routen nach bestimmten Kriterien
     *
     * @param array $routes Liste der Routen
     * @param array $exclude Pfade, die ausgeschlossen werden sollen
     * @return array Gefilterte Routen
     */
    public function filterRoutes(array $routes, array $exclude = []): array
    {
        return array_filter($routes, function ($route) use ($exclude) {
            // Prüfe, ob Route ausgeschlossen werden soll
            foreach ($exclude as $pattern) {
                if (preg_match($pattern, $route)) {
                    return false;
                }
            }

            // Schließe Routen mit Platzhaltern aus (z.B. /users/{id})
            if (strpos($route, '{') !== false && strpos($route, '}') !== false) {
                return false;
            }

            return true;
        });
    }
}
