<?php
/**
 * Shared fetch-lock mechanism for preventing concurrent remote API calls.
 *
 * Uses wp_options as a lightweight distributed lock with TTL expiry
 * to ensure only one PHP process fetches from a given remote endpoint
 * at a time.
 *
 * @package CRTodayCurrencyBlocks
 */

declare(strict_types=1);

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

trait CRToday_Fetch_Lock {

	/**
	 * Build the wp_options key for a given cache key's fetch lock.
	 */
	private static function fetch_lock_option_key(string $cache_key): string {
		return 'crtoday_fetch_lock_' . md5($cache_key);
	}

	/**
	 * Attempt to acquire an exclusive fetch lock.
	 *
	 * Returns true if the lock was acquired, false if another process holds it.
	 * The lock auto-expires after FETCH_LOCK_TTL_SECONDS.
	 */
	private static function try_acquire_fetch_lock(string $cache_key): bool {
		$lock_key = self::fetch_lock_option_key($cache_key);
		$now = time();
		$current_expires = (int) get_option($lock_key, 0);

		if ($current_expires > $now) {
			return false;
		}

		if ($current_expires > 0) {
			delete_option($lock_key);
		}

		return add_option($lock_key, $now + self::FETCH_LOCK_TTL_SECONDS, '', false);
	}

	/**
	 * Release a previously acquired fetch lock.
	 */
	private static function release_fetch_lock(string $cache_key): void {
		delete_option(self::fetch_lock_option_key($cache_key));
	}
}
