<?php
declare(strict_types=1);

namespace FreshCloud\Mail\Cache;

final class InMemoryCache implements CacheInterface
{
    /** @var array<string, array{value: mixed, expiry: float}> */
    private array $items = [];

    public function get(string $key): mixed
    {
        if (!isset($this->items[$key])) {
            return null;
        }

        $item = $this->items[$key];
        if ($item['expiry'] > 0 && $item['expiry'] <= microtime(true)) {
            unset($this->items[$key]);
            return null;
        }

        return $item['value'];
    }

    public function set(string $key, mixed $value, int $ttl = 3600): void
    {
        $this->items[$key] = [
            'value' => $value,
            'expiry' => ($ttl > 0) ? microtime(true) + $ttl : 0,
        ];
    }

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

    public function delete(string $key): void
    {
        unset($this->items[$key]);
    }

    public function clear(): void
    {
        $this->items = [];
    }
}