<?php
/** Update verified per-post GeneratePress layout overrides. */

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

function wpagent_ability_update_generatepress_post_design(): array {
	return array(
		'label'               => __( 'GeneratePress-Beitragsdesign aktualisieren', 'wp-agent-companion' ),
		'description'         => __( 'Ändert individuelle GeneratePress-Layoutvorgaben mit Konfliktschutz, Laufzeitprüfung, Read-back und verifiziertem Rollback.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'properties'           => array(
				'post_id'       => array( 'type' => 'integer', 'minimum' => 1 ),
				'expected_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
				'settings'      => wpagent_generatepress_post_override_schema(),
			),
			'required'             => array( 'post_id', 'expected_hash', 'settings' ),
			'additionalProperties' => false,
		),
		'output_schema'       => array(
			'type'                 => 'object',
			'properties'           => array(
				'post_id'    => array( 'type' => 'integer' ),
				'post_type'  => array( 'type' => 'string' ),
				'overrides'  => wpagent_generatepress_post_override_schema( true ),
				'state_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
				'verified'   => array( 'type' => 'boolean' ),
			),
			'required'             => array( 'post_id', 'post_type', 'overrides', 'state_hash', 'verified' ),
			'additionalProperties' => false,
		),
		'execute_callback'    => 'wpagent_exec_update_generatepress_post_design',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta'                => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_update_generatepress_post_design( $input ) {
	if ( ! wpagent_generatepress_is_active() ) {
		return new WP_Error( 'wpagent_generatepress_inactive', __( 'GeneratePress oder ein GeneratePress-Child-Theme ist nicht aktiv.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	if ( ! wpagent_generatepress_runtime_ready() ) {
		return new WP_Error( 'wpagent_generatepress_runtime_missing', __( 'Die aktive GeneratePress-Version stellt den geprüften Beitragslayout-Weg nicht bereit. Unterstützt wird GeneratePress ab Version 3.6.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	$input = is_array( $input ) ? $input : array();
	$post  = wpagent_generatepress_post_target( absint( $input['post_id'] ?? 0 ) );
	if ( is_wp_error( $post ) ) {
		return $post;
	}
	$schema = wpagent_generatepress_post_override_schema();
	$valid  = rest_validate_value_from_schema( $input['settings'] ?? null, $schema, 'settings' );
	if ( is_wp_error( $valid ) ) {
		return new WP_Error( 'wpagent_generatepress_post_invalid_settings', __( 'Die GeneratePress-Beitragseinstellungen sind ungültig.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$settings = rest_sanitize_value_from_schema( $input['settings'] ?? null, $schema, 'settings' );
	if ( is_wp_error( $settings ) || ! is_array( $settings ) || ! $settings ) {
		return new WP_Error( 'wpagent_generatepress_post_invalid_settings', __( 'Die GeneratePress-Beitragseinstellungen sind ungültig.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}

	$lock = wpagent_generatepress_post_acquire_lock( $post->ID );
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		$previous = wpagent_generatepress_post_snapshot( $post );
		if ( is_wp_error( $previous ) ) {
			return $previous;
		}
		$previous_hash = wpagent_generatepress_post_state_hash( $previous );
		$expected_hash = strtolower( (string) ( $input['expected_hash'] ?? '' ) );
		if ( ! preg_match( '/^[a-f0-9]{64}$/', $expected_hash ) || ! hash_equals( $previous_hash, $expected_hash ) ) {
			return new WP_Error( 'wpagent_generatepress_post_conflict', __( 'Die GeneratePress-Beitragseinstellungen haben sich seit dem Lesen geändert. Lies sie neu und wiederhole den Vorgang.', 'wp-agent-companion' ), array( 'status' => 409, 'current_hash' => $previous_hash ) );
		}
		$expected = wpagent_generatepress_post_expected_snapshot( $previous, $settings );
		$catalog  = wpagent_generatepress_post_field_catalog();
		try {
			foreach ( $settings as $field => $value ) {
				$definition = $catalog[ $field ];
				if ( 'inherit' === $value ) {
					delete_post_meta( $post->ID, $definition['meta'] );
				} else {
					update_post_meta( $post->ID, $definition['meta'], wpagent_generatepress_post_public_to_stored( $value, $definition ) );
				}
			}
		} catch ( Throwable $error ) {
			return wpagent_generatepress_post_fail_after_rollback( $previous, $previous_hash );
		}

		$fresh = wpagent_generatepress_post_snapshot( $post );
		if ( is_wp_error( $fresh ) || ! hash_equals( wpagent_generatepress_post_state_hash( $expected ), wpagent_generatepress_post_state_hash( $fresh ) ) ) {
			return wpagent_generatepress_post_fail_after_rollback( $previous, $previous_hash );
		}
		$overrides = wpagent_generatepress_post_normalize( $fresh );
		$runtime   = wpagent_generatepress_post_runtime_state( $post->ID );
		if ( is_wp_error( $overrides ) || is_wp_error( $runtime ) ) {
			return wpagent_generatepress_post_fail_after_rollback( $previous, $previous_hash );
		}
		foreach ( $settings as $field => $value ) {
			if ( ! isset( $overrides[ $field ] ) || $overrides[ $field ] !== $value || ( 'inherit' !== $value && ( $runtime[ $field ] ?? null ) !== $value ) ) {
				return wpagent_generatepress_post_fail_after_rollback( $previous, $previous_hash );
			}
		}
		return array(
			'post_id'    => (int) $post->ID,
			'post_type'  => $post->post_type,
			'overrides'  => $overrides,
			'state_hash' => wpagent_generatepress_post_state_hash( $fresh ),
			'verified'   => true,
		);
	} finally {
		wpagent_generatepress_post_release_lock( $post->ID, $lock );
	}
}
