<?php
declare(strict_types=1);

namespace App\Core;

final class Cache
{
    private static ?string $dir = null;

    private static function dir(): string
    {
        if (self::$dir === null) {
            self::$dir = Autoloader::basePath() . '/storage/cache';
            if (!is_dir(self::$dir)) {
                @mkdir(self::$dir, 0775, true);
            }
        }
        return self::$dir;
    }

    public static function remember(string $key, int $ttl, callable $factory): mixed
    {
        $file = self::dir() . '/' . md5($key) . '.cache';
        if (file_exists($file) && (time() - filemtime($file)) < $ttl) {
            return unserialize(file_get_contents($file));
        }
        $value = $factory();
        file_put_contents($file, serialize($value), LOCK_EX);
        return $value;
    }

    public static function forget(string $key): void
    {
        @unlink(self::dir() . '/' . md5($key) . '.cache');
    }

    public static function flush(): void
    {
        array_map('unlink', glob(self::dir() . '/*.cache') ?: []);
    }
}
