<?php

declare(strict_types=1);

namespace Archive\Archived;

use App\Framework\View\RenderContext;

final class CacheWarmer
{
    private array $popularTemplates = [];

    public function __construct(
        private readonly SmartCacheEngine $cacheEngine,
        private readonly array $warmupTemplates = []
    ) {}

    public function warmupTemplates(array $templates = []): array
    {
        $templatesToWarm = !empty($templates) ? $templates : $this->warmupTemplates;
        $results = [];

        foreach ($templatesToWarm as $template => $data) {
            $startTime = microtime(true);

            try {
                $context = new RenderContext($template, $data ?? []);
                $this->cacheEngine->render($context);

                $duration = microtime(true) - $startTime;
                $results[$template] = [
                    'success' => true,
                    'duration' => round($duration * 1000, 2) . 'ms'
                ];

            } catch (\Exception $e) {
                $results[$template] = [
                    'success' => false,
                    'error' => $e->getMessage()
                ];
            }
        }

        return $results;
    }

    public function addPopularTemplate(string $template, array $data = []): void
    {
        $this->popularTemplates[$template] = $data;
    }

    public function warmupPopularTemplates(): array
    {
        return $this->warmupTemplates($this->popularTemplates);
    }

    public function scheduleWarmup(array $templates): void
    {
        // In einer echten Implementierung könnte hier ein Background-Job gescheduled werden
        foreach ($templates as $template => $data) {
            $this->addPopularTemplate($template, $data);
        }
    }
}
