<?php

declare(strict_types=1);

namespace App\Framework\Router;

use App\Framework\Attributes\Route;
use App\Framework\Context\ContextType;
use App\Framework\Core\PathProvider;
use App\Framework\Core\RouteCache;
use App\Framework\Core\RouteCompiler;
use App\Framework\DI\DefaultContainer;
use App\Framework\DI\Initializer;
use App\Framework\Discovery\Results\DiscoveryRegistry;

/**
 * Verantwortlich für die Einrichtung des Routers
 */
final readonly class RouterSetup
{
    public function __construct(
        private DefaultContainer $container,
        private RouteCompiler    $routeCompiler,
        private DiscoveryRegistry $results,
    ) {
    }

    /**
     * Richtet den Router basierend auf den verarbeiteten Attributen ein
     * Nur für Web-Context - CLI braucht keine HTTP-Routes
     */
    #[Initializer(ContextType::WEB)]
    public function __invoke(): Router
    {
        #$routeCache = new RouteCache($this->pathProvider->getCachePath('routes.cache.php'));

        $routeCount = $this->results->attributes->getCount(Route::class);

        if ($routeCount > 0) {
            $discoveredRoutes = $this->results->attributes->get(Route::class);

            // Direct DiscoveredAttribute API
            $optimizedRoutes = $this->routeCompiler->compileOptimized(...$discoveredRoutes);

            // Cache speichern
            #$routeCache->save($optimizedRoutes);

        } else {
            $optimizedRoutes = $this->routeCompiler->compileOptimized();
        }

        $router = new HttpRouter($optimizedRoutes);

        $this->container->bind(CompiledRoutes::class, $optimizedRoutes);
        $this->container->bind(HttpRouter::class, $router);
        $this->container->bind(Router::class, $router); // Interface binding

        return $router;
    }
}
