<?php

declare(strict_types=1);

namespace Fennec\Routing;

/**
 * Écrit et lit le fichier de cache compilé des routes, pour éviter un scan Reflection à chaque requête.
 */
final class RouteCache
{
    public function __construct(private readonly string $cacheFilePath)
    {
    }

    public function exists(): bool
    {
        return \is_file($this->cacheFilePath);
    }

    /**
     * @param list<RouteDefinition> $definitions
     *
     * @throws \RuntimeException Si le répertoire de cache ne peut pas être créé.
     */
    public function write(array $definitions): void
    {
        $directory = \dirname($this->cacheFilePath);

        if (!\is_dir($directory) && !\mkdir($directory, recursive: true) && !\is_dir($directory)) {
            throw new \RuntimeException(\sprintf('Could not create cache directory "%s".', $directory));
        }

        $data = \array_map(static fn (RouteDefinition $definition): array => $definition->toArray(), $definitions);
        $exported = \var_export($data, true);

        \file_put_contents($this->cacheFilePath, "<?php\n\nreturn {$exported};\n");
    }

    /**
     * @return list<RouteDefinition>
     */
    public function read(): array
    {
        /** @var list<array{path: string, methods: list<string>, controllerClass: string, controllerMethod: string}> $data */
        $data = require $this->cacheFilePath;

        return \array_map(RouteDefinition::fromArray(...), $data);
    }
}
