<?php
/**
 * Transient cache for Brevo API reads.
 *
 * @package RewindBrevoFormBridge
 */

namespace RewindBrevoFormBridge\Api;

defined( 'ABSPATH' ) || exit;

/**
 * Transient wrapper: 15-minute TTL, keys namespaced rbfb_cache_, explicit
 * flush. Lists and attributes both read through this so no admin page load
 * ever hits Brevo without a cached copy or an explicit refresh click.
 *
 * @since 0.2.0
 */
class Cache {

	/**
	 * Key namespace prefix.
	 *
	 * @var string
	 */
	const PREFIX = 'rbfb_cache_';

	/**
	 * Cache TTL in seconds (15 minutes).
	 *
	 * @var int
	 */
	const TTL = 15 * MINUTE_IN_SECONDS;

	/**
	 * Known cache keys, so flush() can clear them without a table scan.
	 *
	 * @var string[]
	 */
	const KEYS = array( 'lists', 'folders', 'attributes', 'templates', 'senders' );

	/**
	 * Read a cached value.
	 *
	 * @since 0.2.0
	 * @param string $key Bare key, e.g. 'lists'.
	 * @return mixed False when absent or expired (get_transient semantics).
	 */
	public function get( string $key ) {
		return get_transient( self::PREFIX . $key );
	}

	/**
	 * Store a value for the standard TTL.
	 *
	 * @since 0.2.0
	 * @param string $key   Bare key.
	 * @param mixed  $value Value to store. Do not store false — it is
	 *                      indistinguishable from a miss.
	 * @return void
	 */
	public function set( string $key, $value ): void {
		set_transient( self::PREFIX . $key, $value, self::TTL );
	}

	/**
	 * Delete one cached key.
	 *
	 * @since 0.2.0
	 * @param string $key Bare key.
	 * @return void
	 */
	public function delete( string $key ): void {
		delete_transient( self::PREFIX . $key );
	}

	/**
	 * Flush every known cache key. Called by the explicit "Refresh from
	 * Brevo" button — the only thing that justifies the follow-up API calls.
	 *
	 * @since 0.2.0
	 * @return void
	 */
	public function flush(): void {
		foreach ( self::KEYS as $key ) {
			$this->delete( $key );
		}
	}
}
