<?php
declare(strict_types=1);

class Cache
{
    private string $dir;

    public function __construct(?string $dir = null)
    {
        $this->dir = $dir ?? __DIR__ . '/../../storage/cache';
        if (!is_dir($this->dir)) {
            @mkdir($this->dir, 0777, true);
        }
    }

    public function remember(string $key, int $ttlSeconds, callable $resolver)
    {
        $path = $this->pathForKey($key);
        if (is_file($path)) {
            $payload = json_decode((string)file_get_contents($path), true);
            if (is_array($payload) && isset($payload['expires_at']) && time() < (int)$payload['expires_at']) {
                return $payload['data'] ?? null;
            }
        }

        $data = $resolver();
        file_put_contents($path, json_encode([
            'expires_at' => time() + $ttlSeconds,
            'data' => $data,
        ], JSON_UNESCAPED_UNICODE));

        return $data;
    }

    public function forget(string $key): void
    {
        $path = $this->pathForKey($key);
        if (is_file($path)) {
            @unlink($path);
        }
    }

    private function pathForKey(string $key): string
    {
        return $this->dir . DIRECTORY_SEPARATOR . sha1($key) . '.json';
    }
}
