<?php
/**
 * Sync mutex to prevent overlapping ingestion runs.
 *
 * @package DataStream
 */

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

/**
 * Class DataStream_Sync_Lock
 */
class DataStream_Sync_Lock {

	/**
	 * Transient key for the active lock.
	 */
	private const LOCK_KEY = 'datastream_sync_lock';

	/**
	 * Attempt to acquire the sync lock.
	 *
	 * @return bool True when lock acquired.
	 */
	public static function acquire() {
		if ( self::is_locked() ) {
			return false;
		}

		$timeout = max( 60, absint( DataStream_Config::get( 'sync_lock_timeout' ) ) );

		return set_transient( self::LOCK_KEY, time(), $timeout );
	}

	/**
	 * Release the sync lock.
	 */
	public static function release() {
		delete_transient( self::LOCK_KEY );
	}

	/**
	 * Whether a sync is currently locked.
	 *
	 * @return bool
	 */
	public static function is_locked() {
		return false !== get_transient( self::LOCK_KEY );
	}

	/**
	 * Force-clear a stale lock.
	 */
	public static function force_release() {
		delete_transient( self::LOCK_KEY );
	}
}
