<?php

namespace App\Framework\Cache\Driver;

use App\Framework\Cache\CacheDriver;
use App\Framework\Cache\CacheItem;

final readonly class ApcuCache implements CacheDriver
{

    public function __construct(
        private string $prefix = 'cache:'
    ){}

    private function prefixKey(string $key): string
    {
        return $this->prefix . $key;
    }

    public function get(string $key): CacheItem
    {
        $key = $this->prefixKey($key);

        $success = false;
        $value = apcu_fetch($key, $success);
        if (!$success) {
            return CacheItem::miss($key);
        }

        return CacheItem::hit($key, $value);
    }

    public function set(string $key, string $value, ?int $ttl = null): bool
    {
        $key = $this->prefixKey($key);
        $ttl = $ttl ?? 0;

        return apcu_store($key, $value, $ttl);
    }

    public function has(string $key): bool
    {
        $key = $this->prefixKey($key);
        return apcu_exists($key);
    }

    public function forget(string $key): bool
    {
        $key = $this->prefixKey($key);
        return apcu_delete($key);
    }

    public function clear(): bool
    {
        return apcu_clear_cache();
    }
}
