<?php
/** Update the only verified ASE Free generator-tag switch. */

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

function wpagent_ability_update_ase_free_generator_tag(): array {
	return array(
		'label'               => __( 'ASE-Free-Generatormarkierung aktualisieren', 'wp-agent-companion' ),
		'description'         => __( 'Aktualisiert ausschließlich das geprüfte Entfernen der WordPress-Generator-Meta-Markierung in ASE Free mit Blogbindung, CAS und Read-back.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'properties'           => array(
				'disabled'      => array( 'type' => 'boolean' ),
				'expected_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
			),
			'required'             => array( 'disabled', 'expected_hash' ),
			'additionalProperties' => false,
		),
		'output_schema'       => wpagent_ase_free_generator_output_schema( true ),
		'execute_callback'    => 'wpagent_exec_update_ase_free_generator_tag',
		'permission_callback' => 'wpagent_perm_manage_options',
		'meta'                => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_update_ase_free_generator_tag( $input ) {
	$ready = wpagent_ase_free_generator_require_runtime();
	if ( is_wp_error( $ready ) ) {
		return $ready;
	}
	if ( ! current_user_can( 'manage_options' ) ) {
		return wpagent_ase_free_generator_permission_changed();
	}
	$input    = is_array( $input ) ? $input : array();
	$disabled = $input['disabled'] ?? null;
	$expected = strtolower( (string) ( $input['expected_hash'] ?? '' ) );
	if ( ! is_bool( $disabled ) || ! preg_match( '/^[a-f0-9]{64}$/', $expected ) ) {
		return new WP_Error( 'wpagent_ase_free_generator_invalid', __( 'Der gewünschte ASE-Free-Generatorzustand oder sein Konflikthash ist ungültig.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$lock = wpagent_ase_free_generator_acquire_lock();
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		$ready = wpagent_ase_free_generator_require_runtime();
		if ( is_wp_error( $ready ) ) {
			return $ready;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			return wpagent_ase_free_generator_permission_changed();
		}
		$before = wpagent_ase_free_generator_snapshot();
		if ( is_wp_error( $before ) ) {
			return $before;
		}
		if ( ! wpagent_ase_free_generator_same_blog( $before ) ) {
			return wpagent_ase_free_generator_context_changed();
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			return wpagent_ase_free_generator_permission_changed();
		}
		if ( ! $before['smaller_components_enabled'] ) {
			return new WP_Error( 'wpagent_ase_free_generator_module_disabled', __( 'Die ASE-Free-Gruppe „Disable Smaller Components“ ist nicht aktiv. Aktiviere sie zuerst manuell in ASE Free und lies den Zustand neu.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$before_hash = wpagent_ase_free_generator_state_hash( $before );
		if ( ! hash_equals( $before_hash, $expected ) ) {
			return new WP_Error( 'wpagent_ase_free_generator_conflict', __( 'Die ASE-Free-Einstellungen haben sich seit dem Lesen geändert. Lies sie neu und wiederhole den Vorgang.', 'wp-agent-companion' ), array( 'status' => 409, 'current_hash' => $before_hash ) );
		}
		if ( $before['generator_tag_disabled'] === $disabled ) {
			if ( ! wpagent_ase_free_generator_refresh_lock( $lock ) ) {
				return new WP_Error( 'wpagent_ase_free_generator_lock_lost', __( 'Die ASE-Free-Generatoränderung hat ihre exklusive Sperre verloren.', 'wp-agent-companion' ), array( 'status' => 409 ) );
			}
			if ( ! current_user_can( 'manage_options' ) ) {
				return wpagent_ase_free_generator_permission_changed();
			}
			return wpagent_ase_free_generator_output( $before, true );
		}
		$next_options                                = $before['options'];
		$next_options['disable_head_generator_tag'] = $disabled;
		$next_raw                                    = maybe_serialize( $next_options );
		$expected_snapshot                           = $before;
		$expected_snapshot['raw']                    = $next_raw;
		$expected_snapshot['options']                = $next_options;
		$expected_snapshot['generator_tag_disabled'] = $disabled;
		if ( ! wpagent_ase_free_generator_refresh_lock( $lock ) ) {
			return new WP_Error( 'wpagent_ase_free_generator_lock_lost', __( 'Die ASE-Free-Generatoränderung hat ihre exklusive Sperre verloren.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			return wpagent_ase_free_generator_permission_changed();
		}
		if ( ! wpagent_ase_free_generator_same_blog( $before ) ) {
			return wpagent_ase_free_generator_context_changed();
		}
		global $wpdb;
		$updated       = $wpdb->query(
			$wpdb->prepare(
				"UPDATE {$wpdb->options} SET option_value = %s WHERE option_name = %s AND HEX(option_value) = HEX(%s)",
				$next_raw,
				WPAGENT_ASE_FREE_OPTION,
				$before['raw']
			)
		);
		if ( 1 !== $updated ) {
			wpagent_companion_forget_option_cache( WPAGENT_ASE_FREE_OPTION, in_array( $before['autoload'], wp_autoload_values_to_autoload(), true ) );
			if ( false === $updated && '' !== (string) $wpdb->last_error ) {
				return new WP_Error( 'wpagent_ase_free_generator_storage_failed', __( 'Die ASE-Free-Einstellungen konnten nicht atomar gespeichert werden.', 'wp-agent-companion' ), array( 'status' => 502 ) );
			}
			$fresh = wpagent_ase_free_generator_snapshot();
			return new WP_Error(
				'wpagent_ase_free_generator_conflict',
				__( 'Die ASE-Free-Einstellungen haben sich während der Änderung geändert. Lies sie neu und wiederhole den Vorgang.', 'wp-agent-companion' ),
				array( 'status' => 409, 'current_hash' => is_array( $fresh ) ? wpagent_ase_free_generator_state_hash( $fresh ) : '' )
			);
		}
		wpagent_companion_forget_option_cache( WPAGENT_ASE_FREE_OPTION, in_array( $before['autoload'], wp_autoload_values_to_autoload(), true ) );
		if ( ! wpagent_ase_free_generator_refresh_lock( $lock ) || ! current_user_can( 'manage_options' ) || ! wpagent_ase_free_generator_same_blog( $before ) ) {
			return wpagent_ase_free_generator_recovery_required();
		}
		$fresh = wpagent_ase_free_generator_snapshot();
		if ( is_wp_error( $fresh ) || ! hash_equals( wpagent_ase_free_generator_state_hash( $expected_snapshot ), wpagent_ase_free_generator_state_hash( $fresh ) ) ) {
			return wpagent_ase_free_generator_recovery_required();
		}
		if ( ! wpagent_ase_free_generator_refresh_lock( $lock ) || ! current_user_can( 'manage_options' ) || ! wpagent_ase_free_generator_same_blog( $fresh ) ) {
			return wpagent_ase_free_generator_recovery_required();
		}
		return wpagent_ase_free_generator_output( $fresh, true );
	} finally {
		wpagent_ase_free_generator_release_lock( $lock );
	}
}
