<?php
/**
 * Data Cache.
 *
 * Thin wrapper around the Transients API for persona dashboard data:
 * centralises key naming, named TTL constants, and per-user keys.
 *
 * @package Platform\Helm\Modules\Persona_Dashboards
 */

declare( strict_types = 1 );

namespace Platform\Helm\Modules\Persona_Dashboards;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class DataCache {

	private const KEY_PREFIX = 'platform_helm_pd_';

	/** Raw seconds — plain literals to avoid the OPcache class-const trap. */
	public const TTL_LIVE    = 300;   // 5 min.
	public const TTL_NORMAL  = 900;   // 15 min.
	public const TTL_RELAXED = 3600;  // 1 hour.

	/**
	 * Get a cached value by logical key, or compute + store it.
	 *
	 * @param callable():mixed $compute
	 */
	public function remember( string $key, int $ttl, callable $compute ): mixed {
		$full   = self::KEY_PREFIX . $key;
		$cached = get_transient( $full );
		if ( false !== $cached ) {
			return $cached;
		}
		$fresh = $compute();
		set_transient( $full, $fresh, $ttl );
		return $fresh;
	}

	public function put( string $key, mixed $value, int $ttl ): void {
		set_transient( self::KEY_PREFIX . $key, $value, $ttl );
	}

	public function get( string $key ): mixed {
		$value = get_transient( self::KEY_PREFIX . $key );
		return false === $value ? null : $value;
	}

	public function forget( string $key ): void {
		delete_transient( self::KEY_PREFIX . $key );
	}

	public function user_key( string $base, int $user_id ): string {
		return $base . '_u' . $user_id;
	}
}
