<?php

declare(strict_types=1);

namespace App\Framework\Core;

use App\Framework\Core\Exceptions\InvalidRouteCacheFormatException;
use App\Framework\Core\Exceptions\RouteCacheException;

final readonly class RouteCache
{
    public function __construct(
        private string $cacheFile
    ) {
    }

    public function save(array $routes): bool
    {
        $phpExport = '<?php' . PHP_EOL;
        $phpExport .= '// Automatisch generiert am ' . date('Y-m-d H:i:s') . PHP_EOL;
        $phpExport .= 'use App\\Framework\\Core\\StaticRoute;' . PHP_EOL;
        $phpExport .= 'use App\\Framework\\Core\\DynamicRoute;' . PHP_EOL;
        $phpExport .= 'return ' . PhpObjectExporter::export($routes) . ';' . PHP_EOL;

        if (file_put_contents($this->cacheFile, $phpExport) === false) {
            return false;
        }

        return true;
    }

    public function load(): array
    {
        if (! file_exists($this->cacheFile)) {
            throw new RouteCacheException($this->cacheFile);
        }
        $data = include $this->cacheFile;

        if (! is_array($data)) {
            throw new InvalidRouteCacheFormatException($this->cacheFile);
        }

        return $data;
    }

    public function isFresh(int $expectedMTime): bool
    {
        // Optional: prüfe eine Timestamp-Struktur etc.
        if (! file_exists($this->cacheFile)) {
            return false;
        }

        $mtime = filemtime($this->cacheFile);

        return $mtime !== false && $mtime <= $expectedMTime;
    }
}
