<?php
/**
 * The plugin's source of "now".
 *
 * @package TextTango
 */

declare( strict_types=1 );

namespace TextTango\Support;

defined( 'ABSPATH' ) || exit;

/**
 * A single seam for reading the current time.
 *
 * Everything time-sensitive in the plugin — OTP expiry, attempt lockouts, rate
 * limit windows, reconciliation cutoffs — is security-relevant, and none of it
 * can be tested honestly against the real clock without either sleeping or
 * asserting nothing. Routing those reads through here lets a test move time
 * forward deterministically.
 *
 * {@see self::freeze()} and friends exist only for tests; production code never
 * calls them, so `now()` is `time()`.
 */
final class Clock {

	/**
	 * Fixed timestamp used instead of the system clock, when tests set one.
	 */
	private static ?int $override = null;

	/**
	 * The current Unix timestamp.
	 */
	public static function now(): int {
		return self::$override ?? time();
	}

	/**
	 * Pin the clock to a fixed timestamp. Tests only.
	 *
	 * @param int $timestamp Timestamp to report.
	 */
	public static function freeze( int $timestamp ): void {
		self::$override = $timestamp;
	}

	/**
	 * Move the pinned clock forward. Tests only.
	 *
	 * @param int $seconds Seconds to advance.
	 */
	public static function advance( int $seconds ): void {
		self::$override = self::now() + $seconds;
	}

	/**
	 * Return to the system clock. Tests only.
	 */
	public static function release(): void {
		self::$override = null;
	}
}
