<?php
/**
 * Action Scheduler Cancel Tool.
 *
 * Cancel scheduled actions by ID using as_unschedule_action(). Validates
 * action exists and is in a cancellable state before cancellation.
 *
 * @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;

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

/**
 * Action_Scheduler_Cancel_Tool class.
 */
class Action_Scheduler_Cancel_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Cancels scheduled actions. Can cancel a single action by ID, the next matching action, or all matching actions.';
	}

	/**
	 * 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' => 'Cancel a specific action by ID. If provided, other parameters are ignored.',
				),
				'hook'       => array(
					'type'        => 'string',
					'description' => 'The hook name to match. Required if action_id is not provided.',
				),
				'args'       => array(
					'type'        => 'array',
					'description' => 'Arguments to match (optional).',
					'items'       => array(),
				),
				'group'      => array(
					'type'        => 'string',
					'description' => 'Group to match (optional).',
				),
				'cancel_all' => array(
					'type'        => 'boolean',
					'description' => 'If true, cancels all matching actions. If false, cancels only the next one.',
				),
			),
			'required'   => array(),
		);
	}

	/**
	 * 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.' );
		}

		// Cancel by ID.
		if ( ! empty( $args['action_id'] ) ) {

			$action_id = (int) $args['action_id'];
			$store     = \ActionScheduler::store();

			try {
				$store->cancel_action( $action_id );
			} catch ( \Throwable $e ) {
				return $this->error_response( "Failed to cancel action {$action_id}: " . $e->getMessage() );
			}

			return $this->success_response( 'Action canceled successfully', array( 'action_id' => $action_id ) );
		}

		// Cancel by hook (required if no action_id).
		if ( empty( $args['hook'] ) ) {
			return $this->error_response( 'Either action_id or hook is required.' );
		}

		$hook       = $args['hook'];
		$cb_args    = $args['args'] ?? array();
		$group      = $args['group'] ?? '';
		$cancel_all = isset( $args['cancel_all'] ) ? (bool) $args['cancel_all'] : false;

		if ( $cancel_all ) {
			as_unschedule_all_actions( $hook, $cb_args, $group );
			return $this->success_response(
				'All matching actions canceled',
				array(
					'hook'  => $hook,
					'group' => $group,
				)
			);
		}

		$canceled_id = as_unschedule_action( $hook, $cb_args, $group );

		if ( null === $canceled_id ) {
			return $this->error_response( 'No matching pending action found to cancel.' );
		}

		return $this->success_response(
			'Action canceled successfully',
			array(
				'action_id' => $canceled_id,
				'hook'      => $hook,
			)
		);
	}
}
