<?php
/** Verified Rank Math redirection create, update and delete abilities. */

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

/** @return array<string,mixed> */
function wpagent_rank_math_redirection_write_properties(): array {
	return array(
		'source'      => array( 'type' => 'string', 'minLength' => 2, 'maxLength' => 2048, 'pattern' => '^/[^/]' ),
		'destination' => array( 'type' => 'string', 'maxLength' => 4096 ),
		'http_code'   => array( 'type' => 'integer', 'enum' => array( 301, 302, 307, 410, 451 ), 'default' => 301 ),
		'status'      => array( 'type' => 'string', 'enum' => array( 'active', 'inactive' ), 'default' => 'active' ),
		'ignore_case' => array( 'type' => 'boolean', 'default' => false ),
	);
}

/** @return array<string,mixed> */
function wpagent_rank_math_redirection_write_result_schema( bool $include_created = false ): array {
	$properties = array(
		'redirection' => wpagent_rank_math_redirection_schema(),
		'verified'    => array( 'type' => 'boolean' ),
	);
	$required = array( 'redirection', 'verified' );
	if ( $include_created ) {
		$properties['created'] = array( 'type' => 'boolean' );
		$required[]            = 'created';
	}
	return array( 'type' => 'object', 'properties' => $properties, 'required' => $required, 'additionalProperties' => false );
}

function wpagent_ability_create_seo_redirection(): array {
	$properties                             = wpagent_rank_math_redirection_write_properties();
	$properties['expected_collection_hash'] = array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' );
	return array(
		'label'               => __( 'SEO-Weiterleitung erstellen', 'wp-agent-companion' ),
		'description'         => __( 'Erstellt eine sichere exakte Rank-Math-Weiterleitung mit Sammlungskonfliktschutz, Kollisions- und Schleifenprüfung sowie verifiziertem Read-back.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'properties'           => $properties,
			'required'             => array( 'source', 'destination', 'http_code', 'expected_collection_hash' ),
			'additionalProperties' => false,
		),
		'output_schema'       => wpagent_rank_math_redirection_write_result_schema( true ),
		'execute_callback'    => 'wpagent_exec_create_seo_redirection',
		'permission_callback' => 'wpagent_perm_rank_math_redirections',
		'meta'                => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => true, 'idempotent' => false ) ),
	);
}

function wpagent_ability_update_seo_redirection(): array {
	$properties                        = wpagent_rank_math_redirection_write_properties();
	$properties['redirection_id']       = array( 'type' => 'integer', 'minimum' => 1 );
	$properties['expected_state_hash'] = array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' );
	return array(
		'label'               => __( 'SEO-Weiterleitung aktualisieren', 'wp-agent-companion' ),
		'description'         => __( 'Aktualisiert eine einfache exakte Rank-Math-Weiterleitung konfliktgeschützt. Unklare Providerzustände bleiben zur manuellen Prüfung erhalten.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'properties'           => $properties,
			'required'             => array( 'redirection_id', 'expected_state_hash' ),
			'additionalProperties' => false,
		),
		'output_schema'       => wpagent_rank_math_redirection_write_result_schema(),
		'execute_callback'    => 'wpagent_exec_update_seo_redirection',
		'permission_callback' => 'wpagent_perm_rank_math_redirections',
		'meta'                => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => true, 'idempotent' => false ) ),
	);
}

function wpagent_ability_delete_seo_redirection(): array {
	return array(
		'label'               => __( 'SEO-Weiterleitung löschen', 'wp-agent-companion' ),
		'description'         => __( 'Verschiebt eine Rank-Math-Weiterleitung nur mit Bestätigung und aktuellem Konflikt-Hash in den Papierkorb und verifiziert das Ergebnis.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'properties'           => array(
				'redirection_id'     => array( 'type' => 'integer', 'minimum' => 1 ),
				'expected_state_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
				'confirm'             => array( 'type' => 'boolean' ),
			),
			'required'             => array( 'redirection_id', 'expected_state_hash', 'confirm' ),
			'additionalProperties' => false,
		),
		'output_schema'       => array(
			'type'                 => 'object',
			'properties'           => array(
				'redirection_id' => array( 'type' => 'integer', 'minimum' => 1 ),
				'deleted'        => array( 'type' => 'boolean' ),
				'verified'       => array( 'type' => 'boolean' ),
			),
			'required'             => array( 'redirection_id', 'deleted', 'verified' ),
			'additionalProperties' => false,
		),
		'execute_callback'    => 'wpagent_exec_delete_seo_redirection',
		'permission_callback' => 'wpagent_perm_rank_math_redirections',
		'meta'                => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => true, 'idempotent' => false ) ),
	);
}

/** @return array<string,mixed> */
function wpagent_rank_math_redirection_provider_data( array $next, int $id = 0, ?array $previous_raw = null ): array {
	$data = is_array( $previous_raw ) ? $previous_raw : array();
	unset( $data['last_accessed'] );
	$data['id']          = $id;
	$data['sources']     = array( array( 'pattern' => ltrim( $next['source'], '/' ), 'comparison' => 'exact', 'ignore' => $next['ignore_case'] ? 'case' : '' ) );
	$data['url_to']      = $next['destination'];
	$data['header_code'] = $next['http_code'];
	$data['status']      = $next['status'];
	return $data;
}

/** @return array<string,mixed>|WP_Error */
function wpagent_rank_math_redirection_load_raw( int $redirection_id, bool $include_trashed = false ) {
	$raw = \RankMath\Redirections\DB::get_redirection_by_id( $redirection_id );
	if ( ! is_array( $raw ) || ( ! $include_trashed && 'trashed' === ( $raw['status'] ?? '' ) ) ) {
		return new WP_Error( 'wpagent_seo_redirection_not_found', __( 'SEO-Weiterleitung nicht gefunden.', 'wp-agent-companion' ), array( 'status' => 404 ) );
	}
	return $raw;
}

/** @return true|WP_Error */
function wpagent_rank_math_redirection_validate_expected_hash( $value, string $current, string $error_code, string $message ) {
	$expected = is_string( $value ) ? strtolower( $value ) : '';
	if ( ! preg_match( '/^[a-f0-9]{64}$/D', $expected ) ) {
		return new WP_Error( 'wpagent_seo_redirection_expected_hash', __( 'Der erwartete Konflikt-Hash muss aus 64 Kleinbuchstaben und Ziffern bestehen.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	return hash_equals( $current, $expected ) ? true : new WP_Error( $error_code, $message, array( 'status' => 409, 'current_hash' => $current ) );
}

/** @param mixed $input @return array<string,mixed>|WP_Error */
function wpagent_exec_create_seo_redirection( $input ) {
	$runtime = wpagent_rank_math_redirection_runtime();
	if ( is_wp_error( $runtime ) ) {
		return $runtime;
	}
	$input = is_array( $input ) ? $input : array();
	$lock  = wpagent_rank_math_redirection_acquire_lock();
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	$created_id      = 0;
	$next            = null;
	$candidate       = null;
	$write_attempted = false;
	try {
		if ( ! wpagent_rank_math_redirection_lock_checkpoint( $lock ) ) {
			return wpagent_rank_math_redirection_recovery_required( 'lock_lost_before_initial_read' );
		}
		if ( ! wpagent_perm_rank_math_redirections() ) {
			return new WP_Error( 'wpagent_seo_redirection_forbidden', __( 'Die Berechtigung zum Schreiben von SEO-Weiterleitungen fehlt.', 'wp-agent-companion' ), array( 'status' => 403 ) );
		}
		$all = wpagent_rank_math_redirection_all_payloads();
		if ( is_wp_error( $all ) ) {
			return $all;
		}
		$hash_check = wpagent_rank_math_redirection_validate_expected_hash(
			$input['expected_collection_hash'] ?? null,
			wpagent_rank_math_redirection_collection_hash( $all ),
			'wpagent_seo_redirection_collection_conflict',
			__( 'Die SEO-Weiterleitungen wurden seit dem Lesen verändert. Bitte erneut auflisten.', 'wp-agent-companion' )
		);
		if ( is_wp_error( $hash_check ) ) {
			return $hash_check;
		}
		$expected_collection_hash = strtolower( (string) ( $input['expected_collection_hash'] ?? '' ) );
		$next = wpagent_rank_math_redirection_next( $input );
		if ( is_wp_error( $next ) ) {
			return $next;
		}
		$collision = wpagent_rank_math_redirection_source_collision( $next['source'], $next['ignore_case'], $all );
		if ( is_array( $collision ) ) {
			$candidate = wpagent_rank_math_redirection_candidate_payload( (int) $collision['redirection_id'], $next );
			if ( wpagent_rank_math_redirection_semantics_match( $collision, $candidate ) ) {
				return array( 'redirection' => $collision, 'created' => false, 'verified' => true );
			}
			return new WP_Error( 'wpagent_seo_redirection_source_conflict', __( 'Für source existiert bereits eine andere exakte Weiterleitung.', 'wp-agent-companion' ), array( 'status' => 409, 'redirection_id' => $collision['redirection_id'] ) );
		}
		$graph = wpagent_rank_math_redirection_validate_graph( wpagent_rank_math_redirection_candidate_payload( 0, $next ), $all );
		if ( is_wp_error( $graph ) ) {
			return $graph;
		}
		if ( ! wpagent_rank_math_redirection_lock_checkpoint( $lock ) ) {
			return wpagent_rank_math_redirection_recovery_required( 'lock_lost_before_provider_write' );
		}
		if ( ! wpagent_perm_rank_math_redirections() ) {
			return new WP_Error( 'wpagent_seo_redirection_forbidden', __( 'Die Berechtigung zum Schreiben von SEO-Weiterleitungen fehlt.', 'wp-agent-companion' ), array( 'status' => 403 ) );
		}
		$prewrite_all = wpagent_rank_math_redirection_all_payloads();
		if ( is_wp_error( $prewrite_all ) ) {
			return wpagent_rank_math_redirection_recovery_required( 'collection_unavailable_before_provider_write' );
		}
		if ( ! hash_equals( $expected_collection_hash, wpagent_rank_math_redirection_collection_hash( $prewrite_all ) ) ) {
			return new WP_Error( 'wpagent_seo_redirection_collection_conflict', __( 'Die SEO-Weiterleitungen wurden vor dem Speichern verändert. Bitte erneut auflisten.', 'wp-agent-companion' ), array( 'status' => 409, 'current_hash' => wpagent_rank_math_redirection_collection_hash( $prewrite_all ) ) );
		}
		$prewrite_collision = wpagent_rank_math_redirection_source_collision( $next['source'], $next['ignore_case'], $prewrite_all );
		if ( is_array( $prewrite_collision ) ) {
			return new WP_Error( 'wpagent_seo_redirection_source_conflict', __( 'Für source existiert bereits eine andere exakte Weiterleitung.', 'wp-agent-companion' ), array( 'status' => 409, 'redirection_id' => $prewrite_collision['redirection_id'] ) );
		}
		$prewrite_graph = wpagent_rank_math_redirection_validate_graph( wpagent_rank_math_redirection_candidate_payload( 0, $next ), $prewrite_all );
		if ( is_wp_error( $prewrite_graph ) ) {
			return $prewrite_graph;
		}
		$item       = \RankMath\Redirections\Redirection::from( wpagent_rank_math_redirection_provider_data( $next ) );
		$write_attempted = true;
		$created_id = absint( $item->save() );
		if ( $created_id < 1 ) {
			return wpagent_rank_math_redirection_recovery_required( 'provider_create_returned_no_owned_id' );
		}
		if ( ! wpagent_rank_math_redirection_lock_checkpoint( $lock ) || ! wpagent_perm_rank_math_redirections() ) {
			return wpagent_rank_math_redirection_recovery_required( 'lock_or_capability_lost_after_provider_write', $created_id );
		}
		$expected  = wpagent_rank_math_redirection_candidate_payload( $created_id, $next );
		$fresh     = wpagent_rank_math_redirection_record( $created_id );
		$candidate = wpagent_rank_math_redirection_capture_owned_candidate( $created_id, $expected );
		if ( ! is_array( $candidate ) || is_wp_error( $fresh ) || ! wpagent_rank_math_redirection_semantics_match( $fresh, $expected ) ) {
			return wpagent_rank_math_redirection_rollback_error( null, $candidate, $lock, 'create_readback_unverified' );
		}
		if ( ! wpagent_rank_math_redirection_lock_checkpoint( $lock ) || ! wpagent_perm_rank_math_redirections() ) {
			return wpagent_rank_math_redirection_recovery_required( 'lock_or_capability_lost_after_readback', $created_id );
		}
		return array( 'redirection' => $fresh, 'created' => true, 'verified' => true );
	} catch ( Throwable ) {
		if ( $created_id > 0 && is_array( $next ) ) {
			$candidate = is_array( $candidate ) ? $candidate : wpagent_rank_math_redirection_capture_owned_candidate( $created_id, wpagent_rank_math_redirection_candidate_payload( $created_id, $next ) );
			return wpagent_rank_math_redirection_rollback_error( null, $candidate, $lock, 'create_provider_exception_after_owned_id' );
		}
		return wpagent_rank_math_redirection_recovery_required( $write_attempted ? 'create_provider_exception_without_owned_id' : 'create_exception_before_provider_write' );
	} finally {
		wpagent_rank_math_redirection_release_lock( $lock );
	}
}

/** @param mixed $input @return array<string,mixed>|WP_Error */
function wpagent_exec_update_seo_redirection( $input ) {
	$runtime = wpagent_rank_math_redirection_runtime();
	if ( is_wp_error( $runtime ) ) {
		return $runtime;
	}
	$input = is_array( $input ) ? $input : array();
	$id    = absint( $input['redirection_id'] ?? 0 );
	$lock  = wpagent_rank_math_redirection_acquire_lock();
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	$previous_raw = null;
	$previous     = null;
	$next         = null;
	$candidate    = null;
	$written      = false;
	try {
		if ( ! wpagent_rank_math_redirection_lock_checkpoint( $lock ) ) {
			return wpagent_rank_math_redirection_recovery_required( 'lock_lost_before_initial_read', $id );
		}
		if ( ! wpagent_perm_rank_math_redirections() ) {
			return new WP_Error( 'wpagent_seo_redirection_forbidden', __( 'Die Berechtigung zum Schreiben von SEO-Weiterleitungen fehlt.', 'wp-agent-companion' ), array( 'status' => 403 ) );
		}
		$previous_raw = wpagent_rank_math_redirection_load_raw( $id );
		if ( is_wp_error( $previous_raw ) ) {
			return $previous_raw;
		}
		$previous = wpagent_rank_math_redirection_payload( $previous_raw, false );
		if ( is_wp_error( $previous ) ) {
			return $previous;
		}
		if ( ! $previous['writable'] ) {
			return new WP_Error( 'wpagent_seo_redirection_readonly', __( 'Komplexe Rank-Math-Regeln mit mehreren Quellen oder nicht exaktem Vergleich sind schreibgeschützt.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$hash_check = wpagent_rank_math_redirection_validate_expected_hash(
			$input['expected_state_hash'] ?? null,
			$previous['state_hash'],
			'wpagent_seo_redirection_conflict',
			__( 'Die SEO-Weiterleitung wurde seit dem Lesen verändert. Bitte erneut lesen.', 'wp-agent-companion' )
		);
		if ( is_wp_error( $hash_check ) ) {
			return $hash_check;
		}
		$next = wpagent_rank_math_redirection_next( $input, $previous );
		if ( is_wp_error( $next ) ) {
			return $next;
		}
		$all = wpagent_rank_math_redirection_all_payloads();
		if ( is_wp_error( $all ) ) {
			return $all;
		}
		$collision = wpagent_rank_math_redirection_source_collision( $next['source'], $next['ignore_case'], $all, $id );
		if ( is_array( $collision ) ) {
			return new WP_Error( 'wpagent_seo_redirection_source_conflict', __( 'Für source existiert bereits eine andere exakte Weiterleitung.', 'wp-agent-companion' ), array( 'status' => 409, 'redirection_id' => $collision['redirection_id'] ) );
		}
		$candidate = wpagent_rank_math_redirection_candidate_payload( $id, $next );
		$graph     = wpagent_rank_math_redirection_validate_graph( $candidate, $all, $id );
		if ( is_wp_error( $graph ) ) {
			return $graph;
		}
		if ( ! wpagent_rank_math_redirection_lock_checkpoint( $lock ) ) {
			return wpagent_rank_math_redirection_recovery_required( 'lock_lost_before_provider_write', $id );
		}
		if ( ! wpagent_perm_rank_math_redirections() ) {
			return new WP_Error( 'wpagent_seo_redirection_forbidden', __( 'Die Berechtigung zum Schreiben von SEO-Weiterleitungen fehlt.', 'wp-agent-companion' ), array( 'status' => 403 ) );
		}
		$prewrite_raw = wpagent_rank_math_redirection_load_raw( $id );
		if ( is_wp_error( $prewrite_raw ) ) {
			return wpagent_rank_math_redirection_recovery_required( 'record_unavailable_before_provider_write', $id );
		}
		$prewrite = wpagent_rank_math_redirection_payload( $prewrite_raw, false );
		if ( is_wp_error( $prewrite ) ) {
			return wpagent_rank_math_redirection_recovery_required( 'record_invalid_before_provider_write', $id );
		}
		if ( ! hash_equals( $previous['state_hash'], $prewrite['state_hash'] ) ) {
			return new WP_Error( 'wpagent_seo_redirection_conflict', __( 'Die SEO-Weiterleitung wurde vor dem Speichern verändert. Bitte erneut lesen.', 'wp-agent-companion' ), array( 'status' => 409, 'current_hash' => $prewrite['state_hash'] ) );
		}
		$prewrite_all = wpagent_rank_math_redirection_all_payloads();
		if ( is_wp_error( $prewrite_all ) ) {
			return wpagent_rank_math_redirection_recovery_required( 'collection_unavailable_before_provider_write', $id );
		}
		$prewrite_collision = wpagent_rank_math_redirection_source_collision( $next['source'], $next['ignore_case'], $prewrite_all, $id );
		if ( is_array( $prewrite_collision ) ) {
			return new WP_Error( 'wpagent_seo_redirection_source_conflict', __( 'Für source existiert bereits eine andere exakte Weiterleitung.', 'wp-agent-companion' ), array( 'status' => 409, 'redirection_id' => $prewrite_collision['redirection_id'] ) );
		}
		$prewrite_graph = wpagent_rank_math_redirection_validate_graph( $candidate, $prewrite_all, $id );
		if ( is_wp_error( $prewrite_graph ) ) {
			return $prewrite_graph;
		}
		$item    = \RankMath\Redirections\Redirection::from( wpagent_rank_math_redirection_provider_data( $next, $id, $previous_raw ) );
		$written = true;
		$result  = $item->save();
		if ( $id !== absint( $result ) ) {
			return wpagent_rank_math_redirection_recovery_required( 'provider_update_returned_unexpected_id', $id );
		}
		if ( ! wpagent_rank_math_redirection_lock_checkpoint( $lock ) || ! wpagent_perm_rank_math_redirections() ) {
			return wpagent_rank_math_redirection_recovery_required( 'lock_or_capability_lost_after_provider_write', $id );
		}
		$expected_candidate = $candidate;
		$fresh              = wpagent_rank_math_redirection_record( $id );
		$candidate          = wpagent_rank_math_redirection_capture_owned_candidate( $id, $expected_candidate );
		if ( ! is_array( $candidate ) || is_wp_error( $fresh ) || ! wpagent_rank_math_redirection_semantics_match( $fresh, wpagent_rank_math_redirection_candidate_payload( $id, $next ) ) ) {
			return wpagent_rank_math_redirection_rollback_error( $previous_raw, $candidate, $lock, 'update_readback_unverified' );
		}
		if ( ! wpagent_rank_math_redirection_lock_checkpoint( $lock ) || ! wpagent_perm_rank_math_redirections() ) {
			return wpagent_rank_math_redirection_recovery_required( 'lock_or_capability_lost_after_readback', $id );
		}
		return array( 'redirection' => $fresh, 'verified' => true );
	} catch ( Throwable ) {
		if ( $written && is_array( $previous_raw ) && is_array( $next ) ) {
			$candidate = is_array( $candidate ) ? $candidate : wpagent_rank_math_redirection_capture_owned_candidate( $id, wpagent_rank_math_redirection_candidate_payload( $id, $next ) );
			return wpagent_rank_math_redirection_rollback_error( $previous_raw, $candidate, $lock, 'update_provider_exception' );
		}
		return $written
			? wpagent_rank_math_redirection_recovery_required( 'update_provider_exception_without_owned_candidate', $id )
			: new WP_Error( 'wpagent_seo_redirection_write_failed', __( 'Rank Math konnte die Weiterleitung nicht sicher aktualisieren.', 'wp-agent-companion' ), array( 'status' => 500 ) );
	} finally {
		wpagent_rank_math_redirection_release_lock( $lock );
	}
}

/** @param mixed $input @return array<string,mixed>|WP_Error */
function wpagent_exec_delete_seo_redirection( $input ) {
	$runtime = wpagent_rank_math_redirection_runtime();
	if ( is_wp_error( $runtime ) ) {
		return $runtime;
	}
	$input = is_array( $input ) ? $input : array();
	if ( true !== ( $input['confirm'] ?? false ) ) {
		return new WP_Error( 'wpagent_seo_redirection_confirmation', __( 'Zum Löschen muss confirm ausdrücklich true sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$id   = absint( $input['redirection_id'] ?? 0 );
	$lock = wpagent_rank_math_redirection_acquire_lock();
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	$previous_raw = null;
	$written      = false;
	try {
		if ( ! wpagent_perm_rank_math_redirections() ) {
			return new WP_Error( 'wpagent_seo_redirection_forbidden', __( 'Die Berechtigung zum Löschen von SEO-Weiterleitungen fehlt.', 'wp-agent-companion' ), array( 'status' => 403 ) );
		}
		$previous_raw = wpagent_rank_math_redirection_load_raw( $id );
		if ( is_wp_error( $previous_raw ) ) {
			return $previous_raw;
		}
		$previous = wpagent_rank_math_redirection_payload( $previous_raw, false );
		if ( is_wp_error( $previous ) ) {
			return $previous;
		}
		$hash_check = wpagent_rank_math_redirection_validate_expected_hash(
			$input['expected_state_hash'] ?? null,
			$previous['state_hash'],
			'wpagent_seo_redirection_conflict',
			__( 'Die SEO-Weiterleitung wurde seit dem Lesen verändert. Bitte erneut lesen.', 'wp-agent-companion' )
		);
		if ( is_wp_error( $hash_check ) ) {
			return $hash_check;
		}
		$written = 1 === \RankMath\Redirections\DB::change_status( array( $id ), 'trashed' );
		if ( ! $written ) {
			throw new RuntimeException( 'Rank Math redirection trash failed.' );
		}
		$fresh = wpagent_rank_math_redirection_record( $id, true, false );
		if ( ! wpagent_perm_rank_math_redirections() || ! wpagent_rank_math_redirection_lock_is_owned( $lock ) ) {
			return wpagent_rank_math_redirection_delete_recovery_required( __( 'Die Berechtigung oder die WPAgently-Sperre änderte sich während des Papierkorbvorgangs. Die Weiterleitung wurde nicht zurückgerollt. Prüfe Rank Math im WordPress-Admin.', 'wp-agent-companion' ), $fresh );
		}
		if ( is_wp_error( $fresh ) || ! wpagent_rank_math_redirection_trash_readback_matches( $previous, $fresh ) ) {
			return wpagent_rank_math_redirection_delete_recovery_required( __( 'Der Papierkorbstatus der SEO-Weiterleitung konnte nicht exakt bestätigt werden. Die Weiterleitung wurde nicht zurückgerollt. Prüfe Rank Math im WordPress-Admin.', 'wp-agent-companion' ), $fresh );
		}
		return array( 'redirection_id' => $id, 'deleted' => true, 'verified' => true );
	} catch ( Throwable ) {
		return $written
			? wpagent_rank_math_redirection_delete_recovery_required( __( 'Rank Math meldete nach dem Papierkorbvorgang einen Fehler. Die Weiterleitung wurde nicht zurückgerollt. Prüfe Rank Math im WordPress-Admin.', 'wp-agent-companion' ) )
			: new WP_Error( 'wpagent_seo_redirection_delete_failed', __( 'Rank Math konnte die Weiterleitung nicht sicher löschen.', 'wp-agent-companion' ), array( 'status' => 500 ) );
	} finally {
		wpagent_rank_math_redirection_release_lock( $lock );
	}
}

/** @param array<string,mixed> $before @param array<string,mixed> $after */
function wpagent_rank_math_redirection_trash_readback_matches( array $before, array $after ): bool {
	$expected           = $before;
	$expected['status'] = 'trashed';
	return wpagent_rank_math_redirection_semantics_match( $after, $expected );
}

/** @param array<string,mixed>|WP_Error|null $current */
function wpagent_rank_math_redirection_delete_recovery_required( string $message, $current = null ): WP_Error {
	$data = array( 'status' => 500, 'recovery_required' => true, 'rollback_attempted' => false );
	if ( is_array( $current ) && is_string( $current['state_hash'] ?? null ) ) {
		$data['current_hash'] = $current['state_hash'];
	}
	return new WP_Error( 'wpagent_seo_redirection_delete_recovery_required', $message, $data );
}
