<?php
/**
 * Action Scheduler List Tool.
 *
 * List scheduled actions from Action Scheduler with filtering by hook name,
 * status, and group. Supports pagination for large result sets.
 *
 * @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_List_Tool class.
 */
class Action_Scheduler_List_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Lists scheduled actions from Action Scheduler with optional filtering by hook, group, or status.';
	}

	/**
	 * 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(
				'hook'   => array(
					'type'        => 'string',
					'description' => 'Filter by action hook name.',
				),
				'group'  => array(
					'type'        => 'string',
					'description' => 'Filter by action group.',
				),
				'status' => array(
					'type'        => 'string',
					'description' => 'Filter by status: pending, in-progress, complete, failed, canceled.',
					'enum'        => array( 'pending', 'in-progress', 'complete', 'failed', 'canceled' ),
				),
				'limit'  => array(
					'type'        => 'integer',
					'description' => 'Maximum number of actions to return (default: 25, max: 100).',
				),
				'offset' => array(
					'type'        => 'integer',
					'description' => 'Number of actions to skip (default: 0).',
				),
			),
			'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 true;
	}

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

		// Map 'limit' to 'per_page' for Action Scheduler API
		$limit  = min( isset( $args['limit'] ) ? (int) $args['limit'] : 25, 100 );
		$offset = isset( $args['offset'] ) ? (int) $args['offset'] : 0;

		$query_args = array(
			'per_page' => $limit,
			'offset'   => $offset,
			'orderby'  => 'date',
			'order'    => 'ASC',
		);

		if ( ! empty( $args['hook'] ) ) {
			$query_args['hook'] = $args['hook'];
		}

		if ( ! empty( $args['group'] ) ) {
			$query_args['group'] = $args['group'];
		}

		if ( ! empty( $args['status'] ) ) {
			$query_args['status'] = $args['status'];
		}

		$actions = as_get_scheduled_actions( $query_args, OBJECT );

		if ( empty( $actions ) ) {
			return $this->success_response(
				'No scheduled actions found',
				array(
					'actions'  => array(),
					'count'    => 0,
					'total'    => 0,
					'limit'    => $limit,
					'offset'   => $offset,
					'has_more' => false,
				)
			);
		}

		$store  = \ActionScheduler::store();
		$result = array();

		foreach ( $actions as $action_id => $action ) {
			$schedule   = $action->get_schedule();
			$next_run   = null;
			$recurrence = null;

			if ( $schedule && method_exists( $schedule, 'get_date' ) ) {
				$date     = $schedule->get_date();
				$next_run = $date ? (int) $date->format( 'U' ) : null;
			}

			if ( $schedule && method_exists( $schedule, 'get_recurrence' ) ) {
				$recurrence = $schedule->get_recurrence();
			}

			$result[] = array(
				'id'            => $action_id,
				'hook'          => $action->get_hook(),
				'group'         => $action->get_group(),
				'status'        => $store->get_status( $action_id ),
				'args'          => $action->get_args(),
				'priority'      => method_exists( $action, 'get_priority' ) ? $action->get_priority() : 10,
				'next_run'      => $next_run,
				'next_run_date' => $next_run ? gmdate( 'Y-m-d H:i:s e', $next_run ) : null,
				'recurrence'    => $recurrence,
			);
		}

		$count_args = array_filter(
			array(
				'hook'   => $query_args['hook'] ?? null,
				'group'  => $query_args['group'] ?? null,
				'status' => $query_args['status'] ?? null,
			)
		);
		$total      = (int) $store->query_actions( array_merge( $count_args, array( 'per_page' => 0 ) ), 'count' );

		return $this->success_response(
			'Scheduled actions retrieved successfully',
			array(
				'actions'  => $result,
				'count'    => count( $result ),
				'total'    => $total,
				'limit'    => $limit,
				'offset'   => $offset,
				'has_more' => ( $offset + count( $result ) ) < $total,
			)
		);
	}
}
