<?php

namespace Limb_Chatbot\Includes\Services\Channel_Events;

/**
 * Dispatches channel events to one or more WordPress users.
 *
 * This service is the single entry point for any feature that wants to insert
 * events into the channel-event queue.  It owns only the fan-out write logic
 * — it knows nothing about emails, live-agent states, or admin preferences.
 * Feature-specific concerns (resolving recipients, sending emails) must live
 * in the feature's own event listener.
 *
 * Usage example:
 *
 *   $dispatcher->dispatch(
 *       Channel_Event_Types::ADMIN_NEW_LEAD,
 *       $admin_wp_user_ids,
 *       null,
 *       null,
 *       [ 'lead_id' => 42 ]
 *   );
 *
 * @package Limb_Chatbot
 * @subpackage Services\Channel_Events
 * @since 2.1.0
 */
class Channel_Event_Dispatcher {

	/**
	 * @var Channel_Event_Repository
	 */
	private Channel_Event_Repository $repository;

	/**
	 * @param  Channel_Event_Repository  $repository
	 */
	public function __construct( Channel_Event_Repository $repository ) {
		$this->repository = $repository;
	}

	/**
	 * Fan out one event row per recipient WP user ID.
	 *
	 * @param  string               $event_type            One of {@see Channel_Event_Types}.
	 * @param  int[]                $recipient_wp_user_ids WordPress user IDs to notify.
	 * @param  string|null          $chat_uuid             Optional plugin chat UUID.
	 * @param  string|null          $chatbot_user_uuid     Optional chatbot user (visitor) UUID.
	 * @param  array<string,mixed>  $payload               Arbitrary serialisable context.
	 *
	 * @return int  Number of rows successfully inserted.
	 */
	public function dispatch(
		string $event_type,
		array $recipient_wp_user_ids,
		?string $chat_uuid = null,
		?string $chatbot_user_uuid = null,
		array $payload = []
	): int {
		$inserted = 0;

		foreach ( $recipient_wp_user_ids as $wp_user_id ) {
			$wp_user_id = (int) $wp_user_id;
			if ( $wp_user_id <= 0 ) {
				continue;
			}

			$event = new Channel_Event(
				$event_type,
				$wp_user_id,
				$chat_uuid,
				$chatbot_user_uuid,
				$payload
			);

			if ( $this->repository->insert( $event ) !== null ) {
				++$inserted;
			}
		}

		return $inserted;
	}
}
