<?php

namespace FleekDash\Controllers\Post;

use FleekDash\Core\CacheInvalidationManager;
use FleekDash\Libs\API\ResponseService;

/**
 * Cache helper for PostController list endpoints (authors, tags, labels).
 * Handles transient cache with invalidation awareness.
 *
 * @package FleekDash\Controllers\Post
 */
class PostCacheHelper
{
    /**
     * Get cached data or compute and cache it.
     * Respects CacheInvalidationManager for staleness checks.
     *
     * @param string   $cache_key   Transient key (e.g. fleekdash_authors_post)
     * @param int      $ttl_seconds TTL in seconds (e.g. 5 * MINUTE_IN_SECONDS)
     * @param callable $compute     Callback that returns the data to cache (no args)
     * @return \WP_REST_Response Success response with cached or computed data
     */
    public static function getCachedOrCompute(string $cache_key, int $ttl_seconds, callable $compute): \WP_REST_Response
    {
        $cached = \get_transient($cache_key);

        if ($cached !== false) {
            $cache_timestamp_key = $cache_key . '_timestamp';
            $cache_timestamp = \get_transient($cache_timestamp_key);

            if ($cache_timestamp === false) {
                $invalidation_version = \get_transient('fleekdash_cache_invalidation_version');
                if ($invalidation_version === false) {
                    return ResponseService::success($cached);
                }
                $cache_timestamp = 0;
            }

            if (!CacheInvalidationManager::isCacheStale($cache_key, $cache_timestamp)) {
                return ResponseService::success($cached);
            }
        }

        $data = $compute();
        $cache_timestamp = time();
        \set_transient($cache_key, $data, $ttl_seconds);
        \set_transient($cache_key . '_timestamp', $cache_timestamp, $ttl_seconds);

        return ResponseService::success($data);
    }
}
