<?php
/**
 * Action Scheduler Run Tool.
 *
 * Run a specific scheduled action immediately using ActionScheduler_QueueRunner.
 * Validates action exists and is pending before execution.
 *
 * @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://agenistrator.com/
 *
 * 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;

// Direct access prevention
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Action_Scheduler_Run_Tool class.
 */
class Action_Scheduler_Run_Tool extends Tool {

	/**
	 * Get the tool ID.
	 *
	 * @return string The tool ID.
	 * @since     1.0.0
	 */
	public function get_id() {
		return 'run_scheduled_action';
	}

	/**
	 * Get the tool name.
	 *
	 * @return string The tool name.
	 * @since     1.0.0
	 */
	public function get_name() {
		return __( 'Run Scheduled Action', 'agenistrator' );
	}

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Runs a scheduled action immediately using Action Scheduler\'s safe runner. Handles logging, error tracking, and recurring action rescheduling properly.';
	}

	/**
	 * Get the parameters schema for this tool.
	 *
	 * @return array Parameters schema in JSON Schema format.
	 * @since     1.0.0
	 */
	public function get_parameters() {
		return array(
			'type'       => 'object',
			'properties' => array(
				'action_id' => array(
					'type'        => 'integer',
					'description' => 'The ID of the scheduled action to run.',
				),
			),
			'required'   => array( 'action_id' ),
		);
	}

	/**
	 * Check if the current user can execute this tool.
	 *
	 * @return bool True if the current user has permission.
	 * @since     1.0.0
	 */
	public function current_user_can_execute() {
		return is_super_admin();
	}

	/**
	 * Check if this tool is read-only.
	 *
	 * @return bool True if the tool only reads data.
	 * @since     1.0.0
	 */
	public function is_read_only() {
		return false;
	}

	/**
	 * Execute the tool with the given arguments.
	 *
	 * @param array $args The tool arguments.
	 *
	 * @return array The tool execution result.
	 * @since     1.0.0
	 */
	protected function execute( $args ) {
		if ( ! WordPress_Utils::is_action_scheduler_available() ) {
			return $this->error_response( 'Action Scheduler is not available or not initialized.' );
		}

		$action_id = (int) $args['action_id'];
		$store     = \ActionScheduler::store();
		$action    = $store->fetch_action( $action_id );

		if ( ! $action || ! $action->get_hook() ) {
			return $this->error_response( "Scheduled action with ID {$action_id} not found." );
		}

		$hook   = $action->get_hook();
		$status = $store->get_status( $action_id );

		// Only run pending or failed actions.
		if ( ! in_array( $status, array( 'pending', 'failed' ), true ) ) {
			return $this->error_response( "Action {$action_id} has status '{$status}' and cannot be run. Only pending or failed actions can be run." );
		}

		// Use Action Scheduler's queue runner for safe execution.
		// This handles: logging, error tracking, recurring rescheduling, and proper hooks.
		try {
			\ActionScheduler_QueueRunner::instance()->process_action( $action_id, 'Agenistrator' );
		} catch ( \Throwable $e ) {
			return $this->error_response( 'Action execution failed: ' . $e->getMessage() );
		}

		// Check final status after execution.
		$final_status = $store->get_status( $action_id );

		return $this->success_response(
			'Action processed successfully',
			array(
				'action_id'    => $action_id,
				'hook'         => $hook,
				'args'         => $action->get_args(),
				'final_status' => $final_status,
			)
		);
	}
}
