<?php
/**
 * Capture the Action Scheduler action ID currently being executed so that downstream code (e.g. Product_Sync_Service) can write to its logger without having to pass the ID explicitly through every function.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/utils
 * @author     miniOrange
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Utils;

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

/**
 * Class Current_Action
 *
 * Captures the Action Scheduler action ID currently being executed.
 */
class Current_Action {

	/**
	 * ID of the Action Scheduler action currently executing.
	 *
	 * @var int
	 */
	private static int $id = 0;

	/**
	 * Boot the hooks.
	 */
	public static function init(): void {
		add_action( 'action_scheduler_before_execute', array( __CLASS__, 'set' ), 0, 1 );
		add_action( 'action_scheduler_after_execute', array( __CLASS__, 'clear' ), 0, 0 );
		add_action( 'action_scheduler_execution_ignored', array( __CLASS__, 'clear' ), 0, 0 );
		add_action( 'action_scheduler_failed_execution', array( __CLASS__, 'clear' ), 0, 0 );
	}

	/**
	 * Set current action id.
	 *
	 * @param int $action_id Action ID.
	 */
	public static function set( int $action_id ): void {
		self::$id = absint( $action_id );
	}

	/**
	 * Clear after execution.
	 */
	public static function clear(): void {
		self::$id = 0;
	}

	/**
	 * Get current action id.
	 *
	 * @return int Current action ID.
	 */
	public static function id(): int {
		return self::$id;
	}
}
