<?php

declare(strict_types=1);

namespace App\Framework\View\Caching\Strategies;

use App\Framework\Cache\Cache;
use App\Framework\Cache\CacheKey;
use App\Framework\View\Caching\TemplateContext;

final readonly class ComponentCacheStrategy implements ViewCacheStrategy
{
    public function __construct(private Cache $cache)
    {
    }

    public function shouldCache(TemplateContext $context): bool
    {
        return str_contains($context->template, 'component') ||
            str_contains($context->template, 'partial');
    }

    public function generateKey(TemplateContext $context): CacheKey
    {
        $component = basename($context->template);
        $dataHash = md5(serialize($context->data));

        return CacheKey::fromString("component:{$component}:{$dataHash}");
    }

    public function getTtl(TemplateContext $context): int
    {
        // Komponenten länger cachen da sie wiederverwendbar sind
        return 1800; // 30 minutes
    }

    public function canInvalidate(string $template): bool
    {
        return str_contains($template, 'component') || str_contains($template, 'partial');
    }
}
