<?php

declare(strict_types=1);

namespace App\Framework\View;

use App\Framework\Filesystem\FileStorage;

final readonly class ComponentCache
{
    public function __construct(
        private string $cacheDir = __DIR__ . "/cache/components/",
        private FileStorage $storage = new FileStorage('/'),
    ) {
    }

    public function get(string $componentName, array $data, string $templatePath): ?string
    {
        $hash = $this->generateHash($templatePath, $data);
        $cacheFile = $this->getCacheFile($componentName, $hash);

        return $this->storage->exists($cacheFile) ? $this->storage->get($cacheFile) : null;
    }

    public function set(string $componentName, array $data, string $templatePath, string $output): void
    {
        $hash = $this->generateHash($templatePath, $data);
        $cacheFile = $this->getCacheFile($componentName, $hash);

        $this->storage->createDirectory($this->cacheDir);
        $this->storage->put($cacheFile, $output);
    }

    private function generateHash(string $templatePath, array $data): string
    {
        return md5_file($templatePath) . '_' . md5(serialize($data));
    }

    private function getCacheFile(string $componentName, string $hash): string
    {
        return $this->cacheDir . "/{$componentName}_{$hash}.html";
    }
}
