<?php
/**
 * Ability: wp-agent/list-posts
 *
 * Read-only. Listet Beiträge/Seiten eines Post-Types als schlanke Liste
 * (id, title, status, type, date, slug) mit Such-, Status- und
 * Paginierungs-Filter. Der post_type ist generisch (nicht auf 'post'/'page'
 * hartkodiert), wird aber gegen registrierte, öffentliche Types validiert.
 *
 * @package WPAgentCompanion
 */

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

function wpagent_ability_list_posts(): array {
	return array(
		'label'               => __( 'Beiträge auflisten', 'wp-agent-companion' ),
		'description'         => __( 'Listet Beiträge oder Seiten eines Post-Types mit Suche, Status- und Paginierungs-Filter als schlanke Liste (id, title, status, type, date, slug) plus Gesamtzahl.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'properties'           => array(
				'post_type' => array(
					'type'        => 'string',
					'maxLength'   => 20,
					'pattern'     => '^[a-z0-9_-]{1,20}$',
					'default'     => 'post',
					'description' => __( 'Muss ein registrierter, öffentlicher Post-Type sein (z. B. post, page).', 'wp-agent-companion' ),
				),
				'status'    => array(
					'type'      => 'string',
					'maxLength' => 20,
					'pattern'   => '^[a-z0-9_-]{1,20}$',
					'default'   => 'any',
				),
				'search'    => array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 100 ),
				'per_page'  => array(
					'type'    => 'integer', 'minimum' => 1, 'maximum' => 100,
					'default' => 20,
				),
				'page'      => array(
					'type'    => 'integer', 'minimum' => 1, 'maximum' => 10000,
					'default' => 1,
				),
			),
			'additionalProperties' => false,
		),
		'output_schema'       => array(
			'type'                 => 'object',
			'properties'           => array(
				'items' => array(
					'type'  => 'array', 'maxItems' => 100,
					'items' => array(
						'type'                 => 'object',
						'properties'           => array(
							'id'     => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 2147483647 ),
							'title'  => array( 'type' => 'string', 'maxLength' => 200 ),
							'status' => array( 'type' => 'string', 'maxLength' => 20 ),
							'type'   => array( 'type' => 'string', 'maxLength' => 20 ),
							'date'   => array( 'type' => 'string', 'maxLength' => 32 ),
							'slug'   => array( 'type' => 'string', 'maxLength' => 200 ),
						),
						'required'             => array( 'id', 'title', 'status', 'type', 'date', 'slug' ),
						'additionalProperties' => false,
					),
				),
				'total' => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => 2147483647 ),
			),
			'required'             => array( 'items', 'total' ),
			'additionalProperties' => false,
		),
		'execute_callback'    => 'wpagent_exec_list_posts',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta'                => array(
			'show_in_rest' => true,
			'annotations'  => array(
				'readonly'    => true,
				'destructive' => false,
				'idempotent'  => true,
			),
		),
	);
}

/**
 * @param mixed $input
 * @return array|WP_Error
 */
function wpagent_exec_list_posts( $input ) {
	$input     = is_array( $input ) ? $input : array();
	$post_type = 'post';
	if ( array_key_exists( 'post_type', $input ) ) {
		$post_type = wpagent_core_mutator_bounded_text( $input['post_type'], 20 );
		if ( is_wp_error( $post_type ) || 1 !== preg_match( '/^[a-z0-9_-]{1,20}$/D', $post_type ) ) {
			return new WP_Error( 'wpagent_bad_post_type', __( 'post_type ist ungültig.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
	}

	$type_valid = wpagent_validate_post_type( $post_type );
	if ( is_wp_error( $type_valid ) ) {
		return $type_valid;
	}

	// Grobe Schranke oben ist edit_posts; hier zusätzlich die für den
	// konkreten Post-Type tatsächlich zuständige Capability prüfen (z. B.
	// edit_pages, wenn post_type=page).
	if ( ! current_user_can( wpagent_post_type_edit_cap( $post_type ) ) ) {
		return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung für diesen Post-Type.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}

	$status = 'any';
	if ( array_key_exists( 'status', $input ) ) {
		$status = wpagent_core_mutator_bounded_text( $input['status'], 20 );
		if ( is_wp_error( $status ) || 1 !== preg_match( '/^[a-z0-9_-]{1,20}$/D', $status ) ) {
			return new WP_Error( 'wpagent_bad_post_status', __( 'status ist ungültig.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
	}

	$per_page = 20;
	if ( array_key_exists( 'per_page', $input ) ) {
		$per_page = wpagent_core_schema_input_integer( $input['per_page'], 1, 100, 'per_page' );
		if ( is_wp_error( $per_page ) ) {
			return $per_page;
		}
	}

	$page = 1;
	if ( array_key_exists( 'page', $input ) ) {
		$page = wpagent_core_schema_input_integer( $input['page'], 1, 10000, 'page' );
		if ( is_wp_error( $page ) ) {
			return $page;
		}
	}

	$query_args = array(
		'post_type'           => $post_type,
		'post_status'         => $status,
		'posts_per_page'      => $per_page,
		'paged'               => $page,
		'orderby'             => 'date',
		'order'               => 'DESC',
		'ignore_sticky_posts' => true,
		'no_found_rows'       => false,
	);
	if ( array_key_exists( 'search', $input ) ) {
		$search = wpagent_core_mutator_bounded_text( $input['search'], 100 );
		if ( is_wp_error( $search ) ) {
			return $search;
		}
		$query_args['s'] = $search;
	}

	$query = new WP_Query( $query_args );

	$items = array();
	foreach ( $query->posts as $post ) {
		$item = array(
			'id'     => (int) $post->ID,
			'title'  => wpagent_core_schema_output_text( $post->post_title, 200, 'items.title' ),
			'status' => wpagent_core_schema_output_text( $post->post_status, 20, 'items.status' ),
			'type'   => wpagent_core_schema_output_text( $post->post_type, 20, 'items.type' ),
			'date'   => wpagent_core_schema_output_text( $post->post_date, 32, 'items.date' ),
			'slug'   => wpagent_core_schema_output_text( $post->post_name, 200, 'items.slug' ),
		);
		foreach ( $item as $value ) {
			if ( is_wp_error( $value ) ) {
				return $value;
			}
		}
		$items[] = $item;
	}
	$items = wpagent_core_schema_output_list( $items, 100, 'items' );
	if ( is_wp_error( $items ) ) {
		return $items;
	}
	$total = (int) $query->found_posts;
	if ( $total < 0 || $total > 2147483647 ) {
		return new WP_Error( 'wpagent_core_schema_output_overflow', __( 'Die Gesamtzahl der Beiträge überschreitet die veröffentlichte Sicherheitsgrenze.', 'wp-agent-companion' ), array( 'status' => 500 ) );
	}

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