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

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

function wpagent_ability_update_oceanwp_post_design(): array {
	return array(
		'label'               => __( 'OceanWP-Beitragsdesign aktualisieren', 'wp-agent-companion' ),
		'description'         => __( 'Ändert individuelle OceanWP-Layoutvorgaben mit Konfliktschutz, Laufzeitprüfung, Read-back und fail-closed Recovery bei nicht verifizierter Persistierung.', '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_oceanwp_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_oceanwp_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_oceanwp_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_oceanwp_post_design( $input ) {
	if ( ! wpagent_oceanwp_is_active() ) {
		return new WP_Error( 'wpagent_oceanwp_inactive', __( 'OceanWP oder ein OceanWP-Child-Theme ist nicht aktiv.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	if ( ! wpagent_oceanwp_runtime_ready() ) {
		return new WP_Error( 'wpagent_oceanwp_runtime_missing', __( 'Die aktive OceanWP-Version stellt den geprüften Beitragslayout-Weg nicht bereit. Unterstützt wird OceanWP ab Version 4.1.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	$input = is_array( $input ) ? $input : array();
	$post  = wpagent_oceanwp_post_target( absint( $input['post_id'] ?? 0 ) );
	if ( is_wp_error( $post ) ) {
		return $post;
	}
	$schema = wpagent_oceanwp_post_override_schema();
	$valid  = rest_validate_value_from_schema( $input['settings'] ?? null, $schema, 'settings' );
	if ( is_wp_error( $valid ) ) {
		return new WP_Error( 'wpagent_oceanwp_post_invalid_settings', __( 'Die OceanWP-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_oceanwp_post_invalid_settings', __( 'Die OceanWP-Beitragseinstellungen sind ungültig.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}

	$post_id = $post->ID;
	$lock    = wpagent_oceanwp_post_acquire_lock( $post_id );
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		$post = wpagent_oceanwp_post_target( $post_id );
		if ( is_wp_error( $post ) ) {
			return $post;
		}
		if ( ! wpagent_oceanwp_runtime_ready() ) {
			return new WP_Error( 'wpagent_oceanwp_runtime_missing', __( 'Die aktive OceanWP-Version stellt den geprüften Beitragslayout-Weg nicht bereit. Unterstützt wird OceanWP ab Version 4.1.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$previous = wpagent_oceanwp_post_snapshot( $post );
		if ( is_wp_error( $previous ) ) {
			return $previous;
		}
		$previous_hash = wpagent_oceanwp_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_oceanwp_post_conflict', __( 'Die OceanWP-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_oceanwp_post_expected_snapshot( $previous, $settings );
		$catalog  = wpagent_oceanwp_post_field_catalog();
		if ( ! wpagent_oceanwp_post_refresh_lock( $post_id, $lock ) ) {
			return new WP_Error( 'wpagent_oceanwp_post_lock_lost', __( 'Die OceanWP-Beitragsänderung hat ihre exklusive Sperre verloren.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$write_post = wpagent_oceanwp_post_target( $post_id );
		if ( is_wp_error( $write_post ) ) {
			return $write_post;
		}
		$write_started = false;
		try {
			foreach ( $settings as $field => $value ) {
				if ( ! wpagent_oceanwp_post_refresh_lock( $post_id, $lock ) ) {
					return wpagent_oceanwp_post_lock_lost( $write_started );
				}
				$key           = $catalog[ $field ]['meta'];
				$write_started = true;
				if ( 'inherit' === $value ) {
					delete_post_meta( $write_post->ID, $key );
				} else {
					update_post_meta( $write_post->ID, $key, $value );
				}
				if ( ! wpagent_oceanwp_post_refresh_lock( $post_id, $lock ) ) {
					return wpagent_oceanwp_post_recovery_required( $write_post->ID );
				}
			}
		} catch ( Throwable $error ) {
			return $write_started
				? wpagent_oceanwp_post_recovery_required( $write_post->ID )
				: wpagent_oceanwp_post_persist_failed( false );
		}

		$fresh = wpagent_oceanwp_post_snapshot( $post );
		if ( is_wp_error( $fresh ) || ! hash_equals( wpagent_oceanwp_post_state_hash( $expected ), wpagent_oceanwp_post_state_hash( $fresh ) ) ) {
			return wpagent_oceanwp_post_recovery_required( $post->ID );
		}
		if ( ! wpagent_oceanwp_post_refresh_lock( $post_id, $lock ) ) {
			return wpagent_oceanwp_post_recovery_required( $post->ID );
		}
		$overrides = wpagent_oceanwp_post_normalize( $fresh );
		$runtime   = wpagent_oceanwp_post_runtime_state( $post->ID );
		if ( is_wp_error( $runtime ) ) {
			return wpagent_oceanwp_post_recovery_required( $post->ID );
		}
		foreach ( $settings as $field => $value ) {
			if ( ! isset( $overrides[ $field ] ) || $overrides[ $field ] !== $value || ( 'inherit' !== $value && ( $runtime[ $field ] ?? null ) !== $value ) ) {
				return wpagent_oceanwp_post_recovery_required( $post->ID );
			}
		}
		if ( ! wpagent_oceanwp_post_refresh_lock( $post_id, $lock ) ) {
			return wpagent_oceanwp_post_recovery_required( $post_id );
		}
		$verified_post = wpagent_oceanwp_post_target( $post_id );
		if ( is_wp_error( $verified_post ) ) {
			return wpagent_oceanwp_post_recovery_required( $post_id );
		}
		return array(
			'post_id'    => (int) $verified_post->ID,
			'post_type'  => $verified_post->post_type,
			'overrides'  => $overrides,
			'state_hash' => wpagent_oceanwp_post_state_hash( $fresh ),
			'verified'   => true,
		);
	} finally {
		wpagent_oceanwp_post_release_lock( $post_id, $lock );
	}
}
