<?php
/**
 * Trigger dispatch primitive.
 *
 * This class is intentionally free-tier infrastructure: it knows nothing about
 * rule storage, the `ambh_rule` post type, or rule instances. Its only job is
 * to receive "a trigger fired for this entity" calls from any module (Free or
 * paid add-on) and fan that out, asynchronously, as a generic WordPress action
 * — `ambh_automation_trigger_matched` — that a premium rule engine can listen
 * to. With no such listener registered, this is a safe no-op.
 *
 * @package AmbassadorHub\Automations
 */

namespace AmbassadorHub\Automations;

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

/**
 * Dispatches automation triggers to whichever rule engine (if any) is listening.
 */
final class ScheduleEngine {

	/**
	 * Initialize the Schedule Engine.
	 *
	 * @return void
	 */
	public static function init(): void {
		add_action( 'ambh_schedule_rule_instances', array( self::class, 'schedule_rule_instances' ), 10, 3 );
	}

	/**
	 * Record that a trigger fired for an entity. Safe to call whether or not
	 * a rule engine (premium) is installed — with none installed, this is a
	 * no-op once the async job runs.
	 *
	 * @param string $trigger_id Trigger identifier (e.g., 'account_created').
	 * @param int    $entity_id  Entity identifier.
	 * @param array  $context    Additional context.
	 *
	 * @return void
	 */
	public static function schedule_rules_for_trigger( string $trigger_id, int $entity_id, array $context = array() ): void {

		as_enqueue_async_action(
			'ambh_schedule_rule_instances',
			array(
				$trigger_id,
				$entity_id,
				$context,
			),
			'AmbassadorHub\Automations\ScheduleEngine'
		);
	}

	/**
	 * Fan out a fired trigger to any registered rule engine.
	 *
	 * @param string $trigger_id Trigger identifier (e.g., 'account_created').
	 * @param int    $entity_id  Entity identifier.
	 * @param array  $context    Additional context.
	 *
	 * @return void
	 */
	public static function schedule_rule_instances( string $trigger_id, int $entity_id, array $context = array() ): void {

		/**
		 * Fires when a trigger needs to be matched against configured automation
		 * rules. A premium rule engine hooks in here to look up matching rules
		 * and schedule instances for evaluation. With no listener, this is a
		 * deliberate no-op — the free tier ships the trigger primitive only.
		 *
		 * @since 0.5.0
		 *
		 * @param string $trigger_id Trigger identifier.
		 * @param int    $entity_id  Entity ID.
		 * @param array  $context    Additional context.
		 */
		do_action( 'ambh_automation_trigger_matched', $trigger_id, $entity_id, $context );
	}
}
