<?php
/**
 * Current Action Scheduler execution context.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChanges\Scheduler;

/**
 * Captures the current JJ\'s Post Scheduler action ID without putting it into action arguments.
 */
final class CurrentActionContext {
	private ?int $actionId = null;

	public function register(): void {
		add_action( 'action_scheduler_before_execute', array( $this, 'track' ), 1, 1 );
		add_action( 'action_scheduler_after_execute', array( $this, 'clear' ), 999, 0 );
		add_action( 'action_scheduler_failed_execution', array( $this, 'clear' ), 999, 0 );
		add_action( 'action_scheduler_execution_ignored', array( $this, 'clear' ), 999, 0 );
	}

	public function track( int $action_id ): void {
		if ( ! class_exists( 'ActionScheduler' ) ) {
			return;
		}

		$action = \ActionScheduler::store()->fetch_action( $action_id );

		if (
			$action->get_hook() === WordPressActionSchedulerGateway::HOOK
			&& $action->get_group() === WordPressActionSchedulerGateway::GROUP
		) {
			$this->actionId = $action_id;
		}
	}

	public function clear(): void {
		$this->actionId = null;
	}

	public function actionId(): ?int {
		return $this->actionId;
	}
}
