<?php

/**
 * LolaCore — Hub Request Cache
 *
 * @package LolaCore
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\Hub;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Short-lived idempotency cache for LolaHub remote execution (E3.4 / C1).
 *
 * Orthogonal to the fingerprint guard: request_id prevents double execution,
 * fingerprint prevents stale execution.
 */
final class HubRequestCache
{
    private const TRANSIENT_PREFIX = 'lolacore_hub_req_';

    /**
     * TTL in seconds — long enough for master retries, short enough to avoid stale reuse.
     */
    private const TTL = 300;

    /**
     * @return array<string, mixed>|null
     */
    public function get(string $requestId): ?array
    {
        if ($requestId === '') {
            return null;
        }

        $cached = get_transient(self::TRANSIENT_PREFIX . $requestId);

        return is_array($cached) ? $cached : null;
    }

    /**
     * @param array<string, mixed> $payload
     */
    public function put(string $requestId, array $payload): void
    {
        if ($requestId === '') {
            return;
        }

        set_transient(self::TRANSIENT_PREFIX . $requestId, $payload, self::TTL);
    }
}
