<?php
/**
 * Ability: wp-agent/get-seo-meta
 *
 * @package WPAgentCompanion
 */

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

function wpagent_ability_get_seo_meta(): array {
	$text = array( 'type' => 'string' );
	return array(
		'label'               => __( 'SEO-Meta lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest die gespeicherten SEO-, Robots-, Social- und Cornerstone-Meta des aktiven unterstützten SEO-Plugins in einem einheitlichen Format.', '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'                   => $text,
				'seo_title'                => $text,
				'seo_description'          => $text,
				'focus_keyword'            => $text,
				'canonical_url'            => $text,
				'robots_noindex'           => array( 'type' => 'boolean' ),
				'robots_nofollow'          => array( 'type' => 'boolean' ),
				'open_graph_title'         => $text,
				'open_graph_description'   => $text,
				'twitter_title'            => $text,
				'twitter_description'      => $text,
				'cornerstone_supported'    => array( 'type' => 'boolean' ),
				'cornerstone'              => array( 'type' => array( 'boolean', 'null' ) ),
			),
		),
		'execute_callback'    => 'wpagent_exec_get_seo_meta',
		'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_seo_meta( $input ) {
	$input   = is_array( $input ) ? $input : array();
	$post_id = (int) ( $input['post_id'] ?? 0 );
	if ( $post_id <= 0 || ! 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 ) );
	}
	$plugin = wpagent_detect_seo_plugin();
	if ( 'none' === $plugin ) {
		return new WP_Error( 'wpagent_seo_plugin_missing', __( 'Kein unterstütztes SEO-Plugin aktiv.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	return wpagent_read_seo_meta( $post_id, $plugin );
}
