<?php
/**
 * Control Event Class.
 *
 * Represents a control message (clear, reset, etc.).
 *
 * @package   Agenistrator
 * @since     1.0.0
 * @author    Alex Ruban <alex@maximum.guru>
 * @author    Maximum Software Inc <contact@maximum.software>
 * @license   GPL-3.0-only
 * @link      https://maximum.software/
 *
 * SPDX-FileCopyrightText: 2025-2026 Alex Ruban <alex@maximum.guru>
 * SPDX-FileCopyrightText: 2025-2026 Maximum Software Inc <contact@maximum.software>
 * SPDX-License-Identifier: GPL-3.0-only
 */

namespace Agenistrator\Events;

use Agenistrator\Thread_Event;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Control_Event class.
 */
class Control_Event extends Thread_Event {

	public const ACTION_READY             = 'ready';
	public const ACTION_PROCESSING        = 'processing';
	public const ACTION_STOP              = 'stop';
	public const ACTION_CLEAR             = 'clear';
	public const ACTION_RATE_LIMIT_WAIT   = 'rate_limit_wait';
	public const ACTION_RATE_LIMIT_RESUME = 'rate_limit_resume';

	/**
	 * Action to perform
	 *
	 * @var string
	 */
	private $action;

	/**
	 * Additional parameters
	 *
	 * @var array
	 */
	private $params;

	/**
	 * Constructor.
	 *
	 * @param int    $user_id   The user ID.
	 * @param int    $thread_id The thread ID.
	 * @param string $action    The action to perform.
	 * @param array  $params    Additional parameters.
	 * @since     1.0.0
	 */
	public function __construct( $user_id, $thread_id, $action, $params = array() ) {
		parent::__construct( $user_id, $thread_id );
		$this->action = $action;
		$this->params = $params;
	}

	/**
	 * Get the event type.
	 *
	 * @return string
	 * @since     1.0.0
	 */
	public function get_type() {
		return 'control';
	}

	/**
	 * Get the action.
	 *
	 * @return string
	 * @since     1.0.0
	 */
	public function get_action() {
		return $this->action;
	}

	/**
	 * Get the event data.
	 *
	 * @return array
	 * @since     1.0.0
	 */
	public function get_data() {
		$data = array(
			'action' => $this->action,
		);

		if ( ! empty( $this->params ) ) {
			$data['params'] = $this->params;
		}

		return $data;
	}

	/**
	 * Get the SSE payload for this event.
	 *
	 * @return array
	 * @since     1.0.0
	 */
	public function to_sse_payload() {
		$payload = array_merge(
			parent::to_sse_payload(),
			array( 'action' => $this->action )
		);

		if ( ! empty( $this->params ) ) {
			$payload['params'] = $this->params;
		}

		return $payload;
	}

	/**
	 * Create an event from array data.
	 *
	 * @param array $data The event data.
	 * @return static
	 * @since     1.0.0
	 */
	public static function from_array( $data ) {
		$event_data = $data['data'] ?? $data;

		$event = new static(
			$data['user_id'],
			$data['thread_id'],
			$event_data['action'],
			$event_data['params'] ?? array()
		);

		if ( isset( $data['id'] ) ) {
			$event->set_id( $data['id'] );
		}

		return $event;
	}
}
