<?php

namespace App\Framework\View;

use App\Framework\Core\PathProvider;
use App\Framework\Filesystem\FileStorage;
use App\Framework\Meta\MetaData;
use App\Framework\View\Loading\TemplateLoader;

final readonly class ComponentRenderer
{
    public function __construct(
        private TemplateProcessor $processor,
        private ComponentCache $cache,
        private TemplateLoader    $loader,
        private FileStorage       $storage = new FileStorage,
    ) {}

    public function render(string $componentName, array $data): string
    {
        $path = $this->loader->getComponentPath($componentName);

        if(!$this->storage->exists($path)) {
            return "<!-- Komponente '$componentName' nicht gefunden -->";
        }

        if(!$cached = $this->cache->get($componentName, $data, $path)) {
            return $cached;
        }

        $template = $this->storage->get($path);
        $context = new RenderContext(template: $componentName, metaData: new MetaData(''), data: $data);
        $output = $this->processor->render($context, $template);

        $this->cache->set($componentName, $data, $path, $output);

        return $output;
    }
}
