<?php
/** Explicit internal-to-public document-envelope boundaries for form migration. */

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

/**
 * The migration normalizer keeps provider data private and raw until it calls
 * a public provider ability. Encode only the dynamic positions published by
 * that ability. Public ability wrappers still validate and decode the input.
 *
 * @param array<string,mixed> $input
 * @param array<int,array{path:array<int,string>,kind:string}> $documents
 * @return array<string,mixed>|WP_Error
 */
function wpagent_form_migration_public_document_input( array $input, array $documents ) {
	if ( ! function_exists( 'wpagent_companion_schema_transform_documents' ) ) {
		return new WP_Error( 'wpagent_form_migration_provider_unavailable', __( 'Der geschlossene Formularanbieter-Übergang ist nicht verfügbar.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	return wpagent_companion_schema_transform_documents( $input, $documents, true );
}

/**
 * Decodes a provider's public document output at the sole private migration
 * boundary. The portable normalizer must not mistake an integrity envelope for
 * a provider field and silently omit it from a transfer.
 *
 * @param array<string,mixed> $result
 * @param array<int,array{path:array<int,string>,kind:string}> $documents
 * @return array<string,mixed>|WP_Error
 */
function wpagent_form_migration_public_document_output( array $result, array $documents ) {
	if ( ! function_exists( 'wpagent_companion_schema_transform_documents' ) ) {
		return new WP_Error( 'wpagent_form_migration_provider_unavailable', __( 'Der geschlossene Formularanbieter-Übergang ist nicht verfügbar.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	return wpagent_companion_schema_transform_documents( $result, $documents, false );
}

/** @param array<string,mixed> $input @return array<string,mixed>|WP_Error */
function wpagent_form_migration_gravity_public_write_input( array $input ) {
	return wpagent_form_migration_public_document_input(
		$input,
		array(
			array( 'path' => array( 'fields', '*' ), 'kind' => 'object' ),
			array( 'path' => array( 'notifications', '@' ), 'kind' => 'object' ),
			array( 'path' => array( 'confirmations', '@' ), 'kind' => 'object' ),
		)
	);
}

/** @param array<string,mixed> $input @return array<string,mixed>|WP_Error */
function wpagent_form_migration_formidable_public_write_input( array $input ) {
	return wpagent_form_migration_public_document_input(
		$input,
		array( array( 'path' => array( 'fields', '*' ), 'kind' => 'object' ) )
	);
}

/** @param array<string,mixed> $result @return array<string,mixed>|WP_Error */
function wpagent_form_migration_formidable_public_read_result( array $result ) {
	return wpagent_form_migration_public_document_output(
		$result,
		array( array( 'path' => array( 'fields', '*' ), 'kind' => 'object' ) )
	);
}
