<?php
/** Manual-only change request for existing core reusable blocks (wp_block). */

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

function wpagent_ability_update_reusable_block(): array {
	return array(
		'label'               => __( 'Änderung eines wiederverwendbaren Blocks prüfen', 'wp-agent-companion' ),
		'description'         => __( 'Nimmt keine Remote-Änderung an bestehenden wiederverwendbaren Blöcken vor, weil WordPress keine atomare Compare-and-Write-Operation gegen parallele Editor-Änderungen bereitstellt. Speichere die Änderung im WordPress-Backend.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'properties'           => array(
				'block_id'             => array( 'type' => 'integer', 'minimum' => 1 ),
				'expected_state_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
				'title'                => array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 200 ),
				'content_markdown'     => array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 1048576 ),
			),
			'required'             => array( 'block_id', 'expected_state_hash' ),
			'additionalProperties' => false,
		),
		'output_schema'       => array( 'type' => 'object', 'properties' => array(), 'additionalProperties' => false ),
		'execute_callback'    => 'wpagent_exec_update_reusable_block',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta'                => array(
			'show_in_rest' => true,
			'annotations'  => array(
				'readonly'    => false,
				'destructive' => false,
				// A completed write makes expected_state_hash stale. Retrying an
				// ambiguous HTTP failure would hide that result behind a conflict.
				'idempotent'  => false,
				'manual_only' => true,
			),
		),
	);
}

/** @return WP_Error */
function wpagent_reusable_block_manual_update_only(): WP_Error {
	return new WP_Error(
		'wpagent_reusable_block_update_manual_write_required',
		__( 'WordPress stellt für bestehende wiederverwendbare Blöcke keine nachweisbar atomare Compare-and-Write-Operation bereit. WPAgently ändert diesen Block deshalb nicht. Speichere die Änderung im WordPress-Backend und lies den Block anschließend neu.', 'wp-agent-companion' ),
		array( 'status' => 409, 'manual_only' => true )
	);
}

/** @return WP_Error */
function wpagent_exec_update_reusable_block( $input ) {
	// A current state hash and an application lock cannot serialize wp-admin,
	// REST, CLI, or direct database writers. Do not read or mutate the block.
	return wpagent_reusable_block_manual_update_only();
}
