<?php

namespace App\Drivers;

class CacheDriver
{
    private string $path;
    private int $defaultTtl;

    public function __construct(array $config)
    {
        $this->path = rtrim($config['path'] ?? dirname(__DIR__, 2) . '/storage/cache', '/');
        $this->defaultTtl = (int)($config['ttl'] ?? 3600);

        if (!is_dir($this->path)) {
            @mkdir($this->path, 0775, true);
        }
    }

    public function put(string $key, mixed $value, ?int $ttl = null): bool
    {
        $payload = [
            'expires_at' => time() + ($ttl ?? $this->defaultTtl),
            'value' => $value,
        ];

        return file_put_contents($this->file($key), json_encode($payload)) !== false;
    }

    public function get(string $key, mixed $default = null): mixed
    {
        $file = $this->file($key);
        if (!is_file($file)) {
            return $default;
        }

        $payload = json_decode(file_get_contents($file) ?: '', true);
        if (!$payload || ($payload['expires_at'] ?? 0) < time()) {
            @unlink($file);
            return $default;
        }

        return $payload['value'] ?? $default;
    }

    public function has(string $key): bool
    {
        return $this->get($key, null) !== null;
    }

    public function forget(string $key): bool
    {
        $file = $this->file($key);
        return !is_file($file) || @unlink($file);
    }

    public function increment(string $key, int $ttl): int
    {
        $value = (int)$this->get($key, 0) + 1;
        $this->put($key, $value, $ttl);
        return $value;
    }

    private function file(string $key): string
    {
        return $this->path . '/' . hash('sha256', $key) . '.json';
    }
}
