<?php
/**
 * Ability: wp-agent/list-menus
 *
 * Read-only. Listet alle vorhandenen Navigationsmenüs (nav_menu-Terms) als
 * schlanke Liste (id, name, slug, count).
 *
 * Permission-Callback wpagent_perm_edit_theme_options ist in create-menu.php
 * definiert (siehe dortiger Kommentar); diese Datei referenziert sie nur.
 *
 * @package WPAgentCompanion
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

function wpagent_ability_list_menus(): array {
	return array(
		'label'               => __( 'Menüs auflisten', 'wp-agent-companion' ),
		'description'         => __( 'Listet alle vorhandenen Navigationsmenüs mit ID, Name, Slug und Anzahl der Einträge.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type' => 'object',
		),
		'output_schema'       => array(
			'type'       => 'object',
			'properties' => array(
				'items' => array(
					'type'  => 'array',
					'items' => array(
						'type'       => 'object',
						'properties' => array(
							'id'    => array( 'type' => 'integer' ),
							'name'  => array( 'type' => 'string' ),
							'slug'  => array( 'type' => 'string' ),
							'count' => array( 'type' => 'integer' ),
						),
					),
				),
				'total' => array( 'type' => 'integer' ),
			),
		),
		'execute_callback'    => 'wpagent_exec_list_menus',
		'permission_callback' => 'wpagent_perm_edit_theme_options',
		'meta'                => array(
			'show_in_rest' => true,
			'annotations'  => array(
				'readonly'    => true,
				'destructive' => false,
				'idempotent'  => true,
			),
		),
	);
}

/**
 * @param mixed $input Unused ability input.
 * @return array
 */
function wpagent_exec_list_menus( $input = null ) {
	$menus = wp_get_nav_menus();

	$items = array();
	foreach ( $menus as $menu ) {
		$items[] = array(
			'id'    => (int) $menu->term_id,
			'name'  => $menu->name,
			'slug'  => $menu->slug,
			'count' => (int) $menu->count,
		);
	}

	return array(
		'items' => $items,
		'total' => count( $items ),
	);
}
