<?php
/**
 * Internal event dispatcher (thin wrapper around WP hooks).
 *
 * @package Kutby
 * @since   2.5.0
 */

declare(strict_types=1);

namespace Kutby\Events;

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

/**
 * Class Dispatcher
 */
final class Dispatcher {

	/**
	 * Emit a Kutby event.
	 *
	 * @param string               $event Event name (without kutby/ prefix).
	 * @param array<string, mixed> $payload Payload.
	 * @return void
	 */
	public static function emit( string $event, array $payload = array() ): void {
		$hook = 'kutby/' . ltrim( $event, '/' );

		/**
		 * Dynamic Kutby event.
		 *
		 * @since 2.5.0
		 *
		 * @param array<string, mixed> $payload Payload.
		 */
		do_action( $hook, $payload );

		/**
		 * Catch-all for listeners.
		 *
		 * @since 2.5.0
		 *
		 * @param string               $event   Event name.
		 * @param array<string, mixed> $payload Payload.
		 */
		do_action( 'kutby/event', $event, $payload );
	}

	/**
	 * Listen to a Kutby event.
	 *
	 * @param string   $event    Event name.
	 * @param callable $callback Callback.
	 * @param int      $priority Priority.
	 * @return void
	 */
	public static function listen( string $event, callable $callback, int $priority = 10 ): void {
		add_action( 'kutby/' . ltrim( $event, '/' ), $callback, $priority, 1 );
	}
}
