<?php

declare(strict_types=1);

namespace App\Framework\Router;

use App\Framework\Attributes\Route;
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\DiscoveryResults;

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

    /**
     * Richtet den Router basierend auf den verarbeiteten Attributen ein
     */
    #[Initializer]
    public function __invoke(): HttpRouter
    {
        #$routeCache = new RouteCache($this->pathProvider->getCachePath('routes.cache.php'));

        if ($this->results->has(Route::class)) {
            $discoveryRoutes = $this->results->get(Route::class);

            // DIREKT zu optimierten Routen
            $optimizedRoutes = $this->routeCompiler->compileOptimized($discoveryRoutes);

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

            // FULL COMMIT: Nur CompiledRoutes

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

        $router = new HttpRouter($optimizedRoutes);

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

        return $router;
    }
}
