<?php
/** Safe, conflict-protected Fluent Forms field mutations. */

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

/** @return array<string,mixed> */
function wpagent_fluent_forms_choice_input_schema(): array {
	return array(
		'type' => 'object', 'additionalProperties' => false,
		'properties' => array(
			'label' => array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 255 ),
			'value' => array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 191 ),
		),
		'required' => array( 'label', 'value' ),
	);
}

/** @return array<string,mixed> */
function wpagent_fluent_forms_subfield_input_schema(): array {
	return array(
		'type' => 'object', 'additionalProperties' => false,
		'properties' => array(
			'label' => array( 'type' => 'string', 'maxLength' => 255 ),
			'help_message' => array( 'type' => 'string', 'maxLength' => 1000 ),
			'placeholder' => array( 'type' => 'string', 'maxLength' => 255 ),
			'required' => array( 'type' => 'boolean' ), 'visible' => array( 'type' => 'boolean' ),
			'max_length' => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => 100000 ),
		),
	);
}

/** @return array<string,mixed> */
function wpagent_fluent_forms_subfields_input_schema(): array {
	$schema = wpagent_fluent_forms_subfield_input_schema();
	return array(
		'type' => 'object', 'additionalProperties' => false,
		'properties' => array(
			'first_name' => $schema, 'middle_name' => $schema, 'last_name' => $schema,
			'address_line_1' => $schema, 'address_line_2' => $schema, 'city' => $schema,
			'state' => $schema, 'zip' => $schema, 'country' => $schema,
		),
	);
}

/** @return array<string,mixed> */
function wpagent_fluent_forms_field_patch_input_schema(): array {
	return array(
		'type' => 'object', 'additionalProperties' => false, 'minProperties' => 1,
		'properties' => array(
			'type' => array( 'type' => 'string', 'enum' => array_keys( wpagent_fluent_forms_field_definitions() ) ),
			'label' => array( 'type' => 'string', 'maxLength' => 255 ),
			'help_message' => array( 'type' => 'string', 'maxLength' => 1000 ),
			'placeholder' => array( 'type' => 'string', 'maxLength' => 255 ),
			'required' => array( 'type' => 'boolean' ),
			'default_value' => array( 'type' => 'string', 'maxLength' => 1000 ),
			'default_values' => array( 'type' => 'array', 'maxItems' => 200, 'items' => array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 191 ) ),
			'max_length' => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => 100000 ),
			'min' => array( 'type' => 'number', 'minimum' => -1000000000000, 'maximum' => 1000000000000 ),
			'max' => array( 'type' => 'number', 'minimum' => -1000000000000, 'maximum' => 1000000000000 ),
			'step' => array( 'type' => 'number', 'exclusiveMinimum' => 0, 'maximum' => 1000000000000 ),
			'choices' => array( 'type' => 'array', 'minItems' => 1, 'maxItems' => 200, 'items' => wpagent_fluent_forms_choice_input_schema() ),
			'subfields' => wpagent_fluent_forms_subfields_input_schema(),
			'date_format' => array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 32 ),
			'time_enabled' => array( 'type' => 'boolean' ),
		),
	);
}

/** @param mixed $value */
function wpagent_fluent_forms_clean_field_text( $value ): string {
	return sanitize_text_field( (string) $value );
}

/** @param array<string,mixed> $field @param array<string,mixed> $patch @return array<string,mixed>|WP_Error */
function wpagent_fluent_forms_patch_subfields( array $field, array $patch ) {
	$children = is_array( $field['fields'] ?? null ) ? $field['fields'] : array();
	foreach ( $patch as $key => $changes ) {
		if ( ! isset( $children[ $key ] ) || ! is_array( $children[ $key ] ) || ! is_array( $changes ) ) {
			return new WP_Error( 'wpagent_fluent_forms_subfield_unavailable', __( 'Das angeforderte Unterfeld ist für diesen Feldtyp nicht verfügbar.', 'wp-agent-companion' ), array( 'status' => 400, 'subfield' => sanitize_key( (string) $key ) ) );
		}
		$child      = $children[ $key ];
		$attributes = is_array( $child['attributes'] ?? null ) ? $child['attributes'] : array();
		$settings   = is_array( $child['settings'] ?? null ) ? $child['settings'] : array();
		foreach ( array( 'label', 'help_message' ) as $setting ) {
			if ( array_key_exists( $setting, $changes ) ) {
				$settings[ $setting ] = wpagent_fluent_forms_clean_field_text( $changes[ $setting ] );
			}
		}
		if ( array_key_exists( 'placeholder', $changes ) ) {
			$attributes['placeholder'] = wpagent_fluent_forms_clean_field_text( $changes['placeholder'] );
		}
		if ( array_key_exists( 'max_length', $changes ) ) {
			$max_length              = absint( $changes['max_length'] );
			$attributes['maxlength'] = $max_length > 0 ? $max_length : '';
		}
		if ( array_key_exists( 'visible', $changes ) ) {
			$settings['visible'] = (bool) $changes['visible'];
		}
		if ( array_key_exists( 'required', $changes ) ) {
			if ( ! isset( $settings['validation_rules']['required'] ) || ! is_array( $settings['validation_rules']['required'] ) ) {
				$settings['validation_rules']['required'] = array();
			}
			$settings['validation_rules']['required']['value'] = (bool) $changes['required'];
		}
		$child['attributes'] = $attributes;
		$child['settings']   = $settings;
		$children[ $key ]    = $child;
	}
	$field['fields'] = $children;
	return $field;
}

/** @param mixed $choices @return array<int,array<string,string>>|WP_Error */
function wpagent_fluent_forms_clean_choices( $choices ) {
	if ( ! is_array( $choices ) || ! $choices ) {
		return new WP_Error( 'wpagent_fluent_forms_choices_required', __( 'choices muss mindestens eine Auswahl enthalten.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$clean = array();
	$seen  = array();
	foreach ( $choices as $choice ) {
		$label = wpagent_fluent_forms_clean_field_text( is_array( $choice ) ? ( $choice['label'] ?? '' ) : '' );
		$value = wpagent_fluent_forms_clean_field_text( is_array( $choice ) ? ( $choice['value'] ?? '' ) : '' );
		if ( '' === $label || '' === $value ) {
			return new WP_Error( 'wpagent_fluent_forms_choice_invalid', __( 'Jede Auswahl benötigt eine nicht leere Beschriftung und einen nicht leeren Wert.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		if ( isset( $seen[ $value ] ) ) {
			return new WP_Error( 'wpagent_fluent_forms_choice_duplicate', __( 'Auswahlwerte müssen innerhalb eines Feldes eindeutig sein.', 'wp-agent-companion' ), array( 'status' => 400, 'value' => $value ) );
		}
		$seen[ $value ] = true;
		$clean[]        = array( 'label' => $label, 'value' => $value, 'calc_value' => '' );
	}
	return $clean;
}

/** @param array<string,mixed> $field @param array<string,mixed> $patch @return array<string,mixed>|WP_Error */
function wpagent_fluent_forms_patch_field_definition( array $field, array $patch ) {
	$type        = wpagent_fluent_forms_field_type( $field );
	$definitions = wpagent_fluent_forms_field_definitions();
	if ( 'unsupported' === $type || ! isset( $definitions[ $type ] ) ) {
		return new WP_Error( 'wpagent_fluent_forms_field_unsupported', __( 'Dieser bestehende Fluent-Forms-Feldtyp kann nicht sicher verändert werden.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$supports = $definitions[ $type ]['supports'];
	foreach ( $patch as $setting => $value ) {
		if ( 'type' !== $setting && ! in_array( $setting, $supports, true ) ) {
			return new WP_Error( 'wpagent_fluent_forms_field_setting_unsupported', __( 'Eine angeforderte Feldeinstellung wird von diesem Feldtyp nicht unterstützt.', 'wp-agent-companion' ), array( 'status' => 400, 'field_type' => $type, 'setting' => sanitize_key( (string) $setting ) ) );
		}
	}
	$attributes = is_array( $field['attributes'] ?? null ) ? $field['attributes'] : array();
	$settings   = is_array( $field['settings'] ?? null ) ? $field['settings'] : array();
	if ( array_key_exists( 'label', $patch ) ) {
		$settings['label'] = wpagent_fluent_forms_clean_field_text( $patch['label'] );
	}
	if ( array_key_exists( 'help_message', $patch ) ) {
		$settings['help_message'] = wpagent_fluent_forms_clean_field_text( $patch['help_message'] );
	}
	if ( array_key_exists( 'placeholder', $patch ) ) {
		$attributes['placeholder'] = wpagent_fluent_forms_clean_field_text( $patch['placeholder'] );
	}
	if ( array_key_exists( 'required', $patch ) ) {
		if ( ! isset( $settings['validation_rules']['required'] ) || ! is_array( $settings['validation_rules']['required'] ) ) {
			$settings['validation_rules']['required'] = array();
		}
		$settings['validation_rules']['required']['value'] = (bool) $patch['required'];
	}
	if ( array_key_exists( 'max_length', $patch ) ) {
		$max_length              = absint( $patch['max_length'] );
		$attributes['maxlength'] = $max_length > 0 ? $max_length : '';
	}
	if ( array_key_exists( 'default_value', $patch ) ) {
		$attributes['value'] = wpagent_fluent_forms_clean_field_text( $patch['default_value'] );
	}
	if ( array_key_exists( 'default_values', $patch ) ) {
		$defaults = array_values( array_unique( array_map( 'wpagent_fluent_forms_clean_field_text', (array) $patch['default_values'] ) ) );
		if ( in_array( '', $defaults, true ) ) {
			return new WP_Error( 'wpagent_fluent_forms_default_choice', __( 'Standardwerte dürfen nicht leer sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$attributes['value'] = $defaults;
	}
	if ( 'number' === $type ) {
		foreach ( array( 'min', 'max' ) as $limit ) {
			if ( array_key_exists( $limit, $patch ) ) {
				if ( ! isset( $settings['validation_rules'][ $limit ] ) || ! is_array( $settings['validation_rules'][ $limit ] ) ) {
					$settings['validation_rules'][ $limit ] = array();
				}
				$settings['validation_rules'][ $limit ]['value'] = $patch[ $limit ];
			}
		}
		if ( array_key_exists( 'step', $patch ) ) {
			$settings['number_step'] = $patch['step'];
		}
		$minimum = $settings['validation_rules']['min']['value'] ?? '';
		$maximum = $settings['validation_rules']['max']['value'] ?? '';
		if ( '' !== $minimum && '' !== $maximum && (float) $minimum > (float) $maximum ) {
			return new WP_Error( 'wpagent_fluent_forms_number_range', __( 'min darf nicht größer als max sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$default = $attributes['value'] ?? '';
		if ( '' !== $default ) {
			if ( ! is_numeric( $default ) ) {
				return new WP_Error( 'wpagent_fluent_forms_number_default', __( 'Der Standardwert eines Zahlenfeldes muss numerisch sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
			}
			$number = (float) $default;
			if ( '' !== $minimum && $number < (float) $minimum ) {
				return new WP_Error( 'wpagent_fluent_forms_number_default', __( 'Der Standardwert eines Zahlenfeldes darf nicht kleiner als min sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
			}
			if ( '' !== $maximum && $number > (float) $maximum ) {
				return new WP_Error( 'wpagent_fluent_forms_number_default', __( 'Der Standardwert eines Zahlenfeldes darf nicht größer als max sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
			}
		}
	}
	if ( array_key_exists( 'choices', $patch ) ) {
		$choices = wpagent_fluent_forms_clean_choices( $patch['choices'] );
		if ( is_wp_error( $choices ) ) {
			return $choices;
		}
		$settings['advanced_options'] = $choices;
	}
	if ( in_array( $type, array( 'select', 'multi_select', 'radio', 'checkbox' ), true ) ) {
		$values   = array_column( is_array( $settings['advanced_options'] ?? null ) ? $settings['advanced_options'] : array(), 'value' );
		$defaults = is_array( $attributes['value'] ?? null ) ? $attributes['value'] : array( (string) ( $attributes['value'] ?? '' ) );
		foreach ( $defaults as $default ) {
			if ( '' !== $default && ! in_array( $default, $values, true ) ) {
				return new WP_Error( 'wpagent_fluent_forms_default_choice', __( 'Jeder Standardwert muss einem vorhandenen Auswahlwert entsprechen.', 'wp-agent-companion' ), array( 'status' => 400, 'value' => $default ) );
			}
		}
	}
	if ( array_key_exists( 'date_format', $patch ) ) {
		$date_format = (string) $patch['date_format'];
		if ( ! preg_match( '/^[A-Za-z0-9 .\/:,_-]{1,32}$/', $date_format ) ) {
			return new WP_Error( 'wpagent_fluent_forms_date_format', __( 'date_format enthält nicht unterstützte Zeichen.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$settings['date_format'] = $date_format;
	}
	if ( array_key_exists( 'time_enabled', $patch ) ) {
		$settings['is_time_enabled'] = (bool) $patch['time_enabled'];
	}
	$field['attributes'] = $attributes;
	$field['settings']   = $settings;
	if ( array_key_exists( 'subfields', $patch ) ) {
		$field = wpagent_fluent_forms_patch_subfields( $field, (array) $patch['subfields'] );
		if ( is_wp_error( $field ) ) {
			return $field;
		}
	}
	return $field;
}

/** @param array<int,mixed> $fields */
function wpagent_fluent_forms_find_field_index( array $fields, string $field_key ): int {
	foreach ( $fields as $index => $field ) {
		if ( is_array( $field ) && $field_key === (string) ( $field['attributes']['name'] ?? '' ) ) {
			return (int) $index;
		}
	}
	return -1;
}

/** @param array{service:object,form:mixed} $authorized @param array<string,mixed> $snapshot @param array<string,mixed> $form_fields @param array<string,mixed> $catalog @return array<string,mixed>|WP_Error */
function wpagent_fluent_forms_save_field_structure( array $authorized, array $snapshot, array $form_fields, array $catalog ) {
	return wpagent_fluent_forms_recovery_required( absint( $snapshot['id'] ?? 0 ) );
}

function wpagent_ability_upsert_fluent_form_field(): array {
	return array(
		'label' => __( 'Fluent-Forms-Feld sicher anlegen oder aktualisieren', 'wp-agent-companion' ),
		'description' => __( 'Prüft eine Feldänderung gegen den vollständigen Formular-Hash. Das Speichern bleibt ohne atomare Fluent-Forms-Compare-and-Update-Operation manuell.', 'wp-agent-companion' ),
		'category' => 'wp-agent',
		'input_schema' => array(
			'type' => 'object', 'additionalProperties' => false,
			'properties' => array(
				'form_id' => array( 'type' => 'integer', 'minimum' => 1 ),
				'field_key' => array( 'type' => 'string', 'pattern' => '^[a-z][a-z0-9_-]{0,190}$' ),
				'expected_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
				'after_field_key' => array( 'type' => 'string', 'pattern' => '^[a-z][a-z0-9_-]{0,190}$' ),
				'field' => wpagent_fluent_forms_field_patch_input_schema(),
			),
			'required' => array( 'form_id', 'field_key', 'expected_hash', 'field' ),
		),
		'output_schema' => wpagent_fluent_forms_fields_output_schema(),
		'execute_callback' => 'wpagent_exec_upsert_fluent_form_field',
		'permission_callback' => 'wpagent_perm_fluent_forms_manage',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => false, 'idempotent' => false, 'manual_only' => true ) ),
	);
}

/** @param mixed $input @return array|WP_Error */
function wpagent_exec_upsert_fluent_form_field( $input ) {
	$input         = is_array( $input ) ? $input : array();
	$form_id       = absint( $input['form_id'] ?? 0 );
	$field_key     = wpagent_fluent_forms_validate_field_key( $input['field_key'] ?? '' );
	$expected_hash = wpagent_fluent_forms_validate_fields_hash( $input['expected_hash'] ?? '' );
	if ( is_wp_error( $field_key ) || is_wp_error( $expected_hash ) ) {
		return is_wp_error( $field_key ) ? $field_key : $expected_hash;
	}
	$lock = wpagent_fluent_forms_fields_acquire_lock( $form_id );
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		if ( ! wpagent_fluent_forms_fields_lock_is_owned( $form_id, $lock ) ) {
			return new WP_Error( 'wpagent_fluent_forms_lock_lost', __( 'Die Sperre für dieses Fluent-Forms-Formular ging verloren. Lies den Zustand erneut.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$authorized = wpagent_fluent_forms_get_authorized_form( $input );
		if ( is_wp_error( $authorized ) ) {
			return $authorized;
		}
		$snapshot    = wpagent_fluent_forms_form_payload( $authorized['form'] );
		$form_fields = $snapshot['form_fields'];
		if ( ! isset( $form_fields['fields'] ) || ! is_array( $form_fields['fields'] ) ) {
			return new WP_Error( 'wpagent_fluent_forms_bad_fields', __( 'Die gespeicherte Fluent-Forms-Feldstruktur ist ungültig.', 'wp-agent-companion' ), array( 'status' => 500 ) );
		}
		$current_hash = wpagent_fluent_forms_full_state_hash( $authorized['form'] );
		if ( ! hash_equals( $current_hash, $expected_hash ) ) {
			return new WP_Error( 'wpagent_fluent_forms_conflict', __( 'Das Fluent-Forms-Formular wurde seit dem Lesen verändert.', 'wp-agent-companion' ), array( 'status' => 409, 'current_hash' => $current_hash ) );
		}
		$catalog = wpagent_fluent_forms_field_catalog( $authorized['service'], $form_id );
		if ( is_wp_error( $catalog ) ) {
			return $catalog;
		}
		$fields = $form_fields['fields'];
		$index  = wpagent_fluent_forms_find_field_index( $fields, $field_key );
		$patch  = is_array( $input['field'] ?? null ) ? $input['field'] : array();
		if ( $index >= 0 ) {
			$field = $fields[ $index ];
			$type  = wpagent_fluent_forms_field_type( $field );
			if ( isset( $patch['type'] ) && $type !== (string) $patch['type'] ) {
				return new WP_Error( 'wpagent_fluent_forms_field_type_immutable', __( 'Der Typ eines bestehenden Fluent-Forms-Feldes kann nicht geändert werden. Lege stattdessen ein neues Feld an.', 'wp-agent-companion' ), array( 'status' => 400, 'current_type' => $type ) );
			}
		} else {
			$type = sanitize_key( (string) ( $patch['type'] ?? '' ) );
			if ( '' === $type ) {
				return new WP_Error( 'wpagent_fluent_forms_field_type_required', __( 'Für ein neues Feld ist field.type erforderlich.', 'wp-agent-companion' ), array( 'status' => 400 ) );
			}
			if ( ! isset( $catalog['templates'][ $type ] ) ) {
				return new WP_Error( 'wpagent_fluent_forms_field_type_unavailable', __( 'Dieser Feldtyp ist in der aktiven Fluent-Forms-Installation nicht verfügbar.', 'wp-agent-companion' ), array( 'status' => 400, 'field_type' => $type ) );
			}
			$field                       = $catalog['templates'][ $type ];
			$field['attributes']['name'] = $field_key;
		}
		$field = wpagent_fluent_forms_patch_field_definition( $field, $patch );
		if ( is_wp_error( $field ) ) {
			return $field;
		}
		if ( $index >= 0 ) {
			array_splice( $fields, $index, 1 );
		}
		$after = isset( $input['after_field_key'] ) ? wpagent_fluent_forms_validate_field_key( $input['after_field_key'] ) : '';
		if ( is_wp_error( $after ) ) {
			return $after;
		}
		if ( '' !== $after ) {
			if ( $after === $field_key ) {
				return new WP_Error( 'wpagent_fluent_forms_field_order', __( 'after_field_key darf nicht dem bearbeiteten field_key entsprechen.', 'wp-agent-companion' ), array( 'status' => 400 ) );
			}
			$after_index = wpagent_fluent_forms_find_field_index( $fields, $after );
			if ( $after_index < 0 ) {
				return new WP_Error( 'wpagent_fluent_forms_after_field_missing', __( 'after_field_key wurde im Formular nicht gefunden.', 'wp-agent-companion' ), array( 'status' => 404 ) );
			}
			array_splice( $fields, $after_index + 1, 0, array( $field ) );
		} elseif ( $index >= 0 ) {
			array_splice( $fields, $index, 0, array( $field ) );
		} else {
			$fields[] = $field;
		}
		if ( count( $fields ) > 500 ) {
			return new WP_Error( 'wpagent_fluent_forms_field_limit', __( 'Ein Formular darf über diesen sicheren Pfad höchstens 500 Felder enthalten.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$form_fields['fields'] = array_values( $fields );
		return new WP_Error( 'wpagent_fluent_forms_field_update_manual_only', __( 'Fluent Forms bietet keine atomare Compare-and-Update-Operation für die vollständige Feldstruktur. Ändere das Feld in WordPress manuell, damit parallele Editor-Änderungen erhalten bleiben.', 'wp-agent-companion' ), array( 'status' => 409, 'form_id' => $form_id, 'current_hash' => $current_hash ) );
	} finally {
		wpagent_fluent_forms_fields_release_lock( $form_id, $lock );
	}
}

function wpagent_ability_delete_fluent_form_field(): array {
	return array(
		'label' => __( 'Fluent-Forms-Feld manuell löschen', 'wp-agent-companion' ),
		'description' => __( 'Die Fernlöschung bestehender Fluent-Forms-Felder ist ohne atomare Provider-Prüfung nicht verfügbar. Lösche das Feld manuell in WordPress.', 'wp-agent-companion' ),
		'category' => 'wp-agent',
		'input_schema' => array(
			'type' => 'object', 'additionalProperties' => false,
			'properties' => array(
				'form_id' => array( 'type' => 'integer', 'minimum' => 1 ),
				'field_key' => array( 'type' => 'string', 'pattern' => '^[a-z][a-z0-9_-]{0,190}$' ),
				'expected_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
				'confirm' => array( 'type' => 'boolean' ), 'allow_empty_form' => array( 'type' => 'boolean', 'default' => false ),
			),
			'required' => array( 'form_id', 'field_key', 'expected_hash', 'confirm' ),
		),
		'output_schema' => wpagent_fluent_forms_fields_output_schema(),
		'execute_callback' => 'wpagent_exec_delete_fluent_form_field',
		'permission_callback' => 'wpagent_perm_fluent_forms_manage',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => true, 'idempotent' => false, 'manual_only' => true ) ),
	);
}

/** @param mixed $input @return array|WP_Error */
function wpagent_exec_delete_fluent_form_field( $input ) {
	$input = is_array( $input ) ? $input : array();
	if ( true !== ( $input['confirm'] ?? false ) ) {
		return new WP_Error( 'wpagent_confirmation_required', __( 'Das dauerhafte Löschen des Feldes erfordert confirm=true.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$form_id       = absint( $input['form_id'] ?? 0 );
	$field_key     = wpagent_fluent_forms_validate_field_key( $input['field_key'] ?? '' );
	$expected_hash = wpagent_fluent_forms_validate_fields_hash( $input['expected_hash'] ?? '' );
	if ( is_wp_error( $field_key ) || is_wp_error( $expected_hash ) ) {
		return is_wp_error( $field_key ) ? $field_key : $expected_hash;
	}
	$lock = wpagent_fluent_forms_fields_acquire_lock( $form_id );
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		$authorized = wpagent_fluent_forms_get_authorized_form( $input );
		if ( is_wp_error( $authorized ) ) {
			return $authorized;
		}
		$snapshot    = wpagent_fluent_forms_form_payload( $authorized['form'] );
		$form_fields = $snapshot['form_fields'];
		$fields      = is_array( $form_fields['fields'] ?? null ) ? $form_fields['fields'] : array();
		$current_hash = wpagent_fluent_forms_fields_hash( $form_fields );
		if ( ! hash_equals( $current_hash, $expected_hash ) ) {
			return new WP_Error( 'wpagent_fluent_forms_fields_conflict', __( 'Die Fluent-Forms-Felder wurden seit dem Lesen verändert.', 'wp-agent-companion' ), array( 'status' => 409, 'current_hash' => $current_hash ) );
		}
		$index = wpagent_fluent_forms_find_field_index( $fields, $field_key );
		if ( $index < 0 ) {
			return new WP_Error( 'wpagent_fluent_forms_field_not_found', __( 'Das Fluent-Forms-Feld wurde nicht gefunden.', 'wp-agent-companion' ), array( 'status' => 404 ) );
		}
		if ( 'unsupported' === wpagent_fluent_forms_field_type( $fields[ $index ] ) ) {
			return new WP_Error( 'wpagent_fluent_forms_field_unsupported', __( 'Ein unbekannter Add-on-Feldtyp wird nicht ohne providerspezifische Prüfung gelöscht.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		if ( 1 === count( $fields ) && true !== ( $input['allow_empty_form'] ?? false ) ) {
			return new WP_Error( 'wpagent_fluent_forms_last_field', __( 'Das letzte Formularfeld wird nur mit allow_empty_form=true gelöscht.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$catalog = wpagent_fluent_forms_field_catalog( $authorized['service'], $form_id );
		if ( is_wp_error( $catalog ) ) {
			return $catalog;
		}
		return new WP_Error( 'wpagent_fluent_forms_field_delete_manual_only', __( 'Das Löschen bestehender Fluent-Forms-Felder kann ohne atomare Provider-Prüfung nicht sicher gegen parallele Änderungen abgesichert werden. Lösche das Feld in WordPress manuell.', 'wp-agent-companion' ), array( 'status' => 409, 'form_id' => $form_id, 'field_key' => $field_key ) );
	} finally {
		wpagent_fluent_forms_fields_release_lock( $form_id, $lock );
	}
}
