<?php
/** Read-only Rank Math redirection abilities. */

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

function wpagent_ability_list_seo_redirections(): array {
	return array(
		'label'               => __( 'SEO-Weiterleitungen auflisten', 'wp-agent-companion' ),
		'description'         => __( 'Listet Rank-Math-Weiterleitungen mit Status, Trefferzahl, Veränderbarkeit und einem Konflikt-Hash der vollständigen Sammlung.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'properties'           => array(
				'status'   => array( 'type' => 'string', 'enum' => array( 'any', 'active', 'inactive' ), 'default' => 'any' ),
				'search'   => array( 'type' => 'string', 'maxLength' => 200 ),
				'page'     => array( 'type' => 'integer', 'minimum' => 1, 'default' => 1 ),
				'per_page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 100, 'default' => 20 ),
			),
			'additionalProperties' => false,
		),
		'output_schema'       => array(
			'type'                 => 'object',
			'properties'           => array(
				'redirections'    => array( 'type' => 'array', 'items' => wpagent_rank_math_redirection_schema() ),
				'total'           => array( 'type' => 'integer', 'minimum' => 0 ),
				'page'            => array( 'type' => 'integer', 'minimum' => 1 ),
				'per_page'        => array( 'type' => 'integer', 'minimum' => 1 ),
				'total_pages'     => array( 'type' => 'integer', 'minimum' => 0 ),
				'collection_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
			),
			'required'             => array( 'redirections', 'total', 'page', 'per_page', 'total_pages', 'collection_hash' ),
			'additionalProperties' => false,
		),
		'execute_callback'    => 'wpagent_exec_list_seo_redirections',
		'permission_callback' => 'wpagent_perm_rank_math_redirections',
		'meta'                => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

function wpagent_ability_get_seo_redirection(): array {
	return array(
		'label'               => __( 'SEO-Weiterleitung lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest eine einzelne Rank-Math-Weiterleitung mit Konflikt-Hash und kennzeichnet komplexe Provider-Regeln als schreibgeschützt.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'properties'           => array( 'redirection_id' => array( 'type' => 'integer', 'minimum' => 1 ) ),
			'required'             => array( 'redirection_id' ),
			'additionalProperties' => false,
		),
		'output_schema'       => array(
			'type'                 => 'object',
			'properties'           => array( 'redirection' => wpagent_rank_math_redirection_schema() ),
			'required'             => array( 'redirection' ),
			'additionalProperties' => false,
		),
		'execute_callback'    => 'wpagent_exec_get_seo_redirection',
		'permission_callback' => 'wpagent_perm_rank_math_redirections',
		'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_list_seo_redirections( $input ) {
	$runtime = wpagent_rank_math_redirection_runtime();
	if ( is_wp_error( $runtime ) ) {
		return $runtime;
	}
	$input    = is_array( $input ) ? $input : array();
	$status   = is_string( $input['status'] ?? null ) ? $input['status'] : 'any';
	$search   = is_string( $input['search'] ?? null ) ? trim( $input['search'] ) : '';
	$page     = max( 1, absint( $input['page'] ?? 1 ) );
	$per_page = max( 1, min( 100, absint( $input['per_page'] ?? 20 ) ) );
	if ( ! in_array( $status, array( 'any', 'active', 'inactive' ), true ) ) {
		return new WP_Error( 'wpagent_seo_redirection_status_filter', __( 'status muss any, active oder inactive sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	if ( strlen( $search ) > 200 || ! wp_is_valid_utf8( $search ) ) {
		return new WP_Error( 'wpagent_seo_redirection_search', __( 'search muss gültiges UTF-8 mit höchstens 200 Bytes enthalten.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$all = wpagent_rank_math_redirection_all_payloads();
	if ( is_wp_error( $all ) ) {
		return $all;
	}
	$collection_hash = wpagent_rank_math_redirection_collection_hash( $all );
	$filtered        = array_values(
		array_filter(
			$all,
			static function ( array $redirection ) use ( $status, $search ): bool {
				if ( 'any' !== $status && $status !== $redirection['status'] ) {
					return false;
				}
				if ( '' === $search ) {
					return true;
				}
				$haystack = $redirection['destination'];
				foreach ( $redirection['sources'] as $source ) {
					$haystack .= "\n" . $source['pattern'];
				}
				return false !== stripos( $haystack, $search );
			}
		)
	);
	$total = count( $filtered );
	$items = array_slice( $filtered, ( $page - 1 ) * $per_page, $per_page );
	foreach ( $items as $index => $item ) {
		$filtered_item = apply_filters( 'wpagent_rank_math_redirection_readback', $item, $item['redirection_id'] );
		if ( ! is_array( $filtered_item ) ) {
			return new WP_Error( 'wpagent_seo_redirection_provider_state_invalid', __( 'Der Weiterleitungs-Read-back ist ungültig.', 'wp-agent-companion' ), array( 'status' => 502 ) );
		}
		$items[ $index ] = $filtered_item;
	}
	return array(
		'redirections'    => $items,
		'total'           => $total,
		'page'            => $page,
		'per_page'        => $per_page,
		'total_pages'     => $total > 0 ? (int) ceil( $total / $per_page ) : 0,
		'collection_hash' => $collection_hash,
	);
}

/** @param mixed $input @return array<string,mixed>|WP_Error */
function wpagent_exec_get_seo_redirection( $input ) {
	$runtime = wpagent_rank_math_redirection_runtime();
	if ( is_wp_error( $runtime ) ) {
		return $runtime;
	}
	$input = is_array( $input ) ? $input : array();
	$item  = wpagent_rank_math_redirection_record( absint( $input['redirection_id'] ?? 0 ) );
	return is_wp_error( $item ) ? $item : array( 'redirection' => $item );
}
