<?php
/** Ability: wp-agent/get-post-schema */

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

function wpagent_ability_get_post_schema(): array {
	return array(
		'label'               => __( 'Post-Schema lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest benutzerdefinierte Rank-Math-Schemas oder Yoasts Seiten- und Artikeltyp über bestätigte Providerpfade.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type' => 'object', 'properties' => array( 'post_id' => array( 'type' => 'integer' ) ),
			'required' => array( 'post_id' ), 'additionalProperties' => false,
		),
		'output_schema'       => array(
			'type' => 'object',
			'properties' => array(
				'post_id' => array( 'type' => 'integer' ), 'plugin' => array( 'type' => 'string' ),
				'custom_schema_supported' => array( 'type' => 'boolean' ),
				'page_type' => array( 'type' => array( 'string', 'null' ) ),
				'article_type' => array( 'type' => array( 'string', 'null' ) ),
				'schemas' => array( 'type' => 'array', 'items' => array( 'type' => 'object' ) ),
				'available_types' => array( 'type' => 'array', 'items' => array( 'type' => 'string' ) ),
				'available_page_types' => array( 'type' => 'array', 'items' => array( 'type' => 'string' ) ),
				'available_article_types' => array( 'type' => 'array', 'items' => array( 'type' => 'string' ) ),
				'state_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
			),
			'required' => array( 'post_id', 'plugin', 'custom_schema_supported', 'page_type', 'article_type', 'schemas', 'available_types', 'available_page_types', 'available_article_types', 'state_hash' ),
		),
		'execute_callback'    => 'wpagent_exec_get_post_schema',
		'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<string,mixed>|WP_Error */
function wpagent_exec_get_post_schema( $input ) {
	$input   = is_array( $input ) ? $input : array();
	$post_id = absint( $input['post_id'] ?? 0 );
	if ( ! $post_id || ! get_post( $post_id ) ) {
		return new WP_Error( 'wpagent_no_post', __( 'Beitrag nicht gefunden.', 'wp-agent-companion' ), array( 'status' => 404 ) );
	}
	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	return wpagent_read_post_schema( $post_id, wpagent_detect_seo_plugin() );
}
