<?php

declare(strict_types=1);

namespace Numinix\SeekmodoWordPress\Storage;

use Numinix\SeekmodoSdk\Storage\CacheInterface;

/**
 * WordPress-flavoured implementation of the SDK's
 * {@see CacheInterface}, backed by WP transients (which automatically
 * promote to the persistent object cache when one is installed).
 *
 * Used by:
 *   - {@see \Numinix\SeekmodoSdk\TenantSnapshot} for the 5-min
 *     tenant.snapshot poll cache.
 *   - {@see \Numinix\SeekmodoSdk\BrowserToken} for the 4-min browser
 *     token cache (one mint per page is too expensive).
 *   - {@see \Numinix\SeekmodoSdk\SignatureMismatchTracker} for the
 *     sliding-window failure counter.
 *   - {@see \Numinix\SeekmodoSdk\Pairing} for the 24-hour JWKS cache.
 *
 * Transient names are prefixed with `seekmodo_` so operators can
 * grep for them in `wp_options`.
 */
final class WpObjectCache implements CacheInterface
{
    public const TRANSIENT_PREFIX = 'seekmodo_';

    public function get(string $key, $default = null)
    {
        if (!function_exists('get_transient')) {
            return $default;
        }
        $value = get_transient(self::TRANSIENT_PREFIX . $key);
        // WP transients return `false` for missing keys, which is
        // indistinguishable from a stored `false` value. We accept
        // this collision because every SDK consumer stores arrays /
        // strings / ints, never raw `false`.
        return $value === false ? $default : $value;
    }

    public function set(string $key, $value, int $ttlSeconds): void
    {
        if (!function_exists('set_transient')) {
            return;
        }
        set_transient(self::TRANSIENT_PREFIX . $key, $value, max(1, $ttlSeconds));
    }

    public function delete(string $key): void
    {
        if (!function_exists('delete_transient')) {
            return;
        }
        delete_transient(self::TRANSIENT_PREFIX . $key);
    }
}
