<?php
/**
 * Clone document fragments with unique node IDs (for insert into editor).
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Templates;

use AuraBuilder\Document\Node;

final class TemplateIdRemapper {

	/**
	 * @param array<string, mixed> $document
	 * @return array<string, mixed>
	 */
	public static function remap( array $document ): array {
		$nodes = $document['nodes'] ?? null;
		if ( ! is_array( $nodes ) || ! $nodes ) {
			return $document;
		}

		$id_map = array();
		foreach ( array_keys( $nodes ) as $old ) {
			$id_map[ (string) $old ] = Node::generate_id();
		}

		$root_old = (string) ( $document['rootId'] ?? $document['root_id'] ?? '' );
		if ( $root_old !== '' && ! isset( $id_map[ $root_old ] ) ) {
			$id_map[ $root_old ] = Node::generate_id();
		}

		$new_nodes = array();
		foreach ( $nodes as $old_id => $node ) {
			if ( ! is_array( $node ) ) {
				continue;
			}
			$oid = (string) $old_id;
			$nid = $id_map[ $oid ] ?? Node::generate_id();
			$node['id'] = $nid;

			$parent = $node['parentId'] ?? $node['parent_id'] ?? null;
			if ( $parent !== null && $parent !== '' ) {
				$p = (string) $parent;
				$node['parentId'] = $id_map[ $p ] ?? null;
			} else {
				$node['parentId'] = null;
			}
			unset( $node['parent_id'] );

			$children = $node['children'] ?? array();
			if ( is_array( $children ) ) {
				$node['children'] = array_values(
					array_map(
						static function ( $cid ) use ( $id_map ) {
							$c = (string) $cid;
							return $id_map[ $c ] ?? $c;
						},
						$children
					)
				);
			}
			$new_nodes[ $nid ] = $node;
		}

		$document['nodes']  = $new_nodes;
		$document['rootId'] = $root_old !== '' && isset( $id_map[ $root_old ] )
			? $id_map[ $root_old ]
			: ( array_key_first( $new_nodes ) ?: '' );
		unset( $document['root_id'] );
		$document['id'] = 'tpl_' . wp_generate_password( 8, false, false );

		return $document;
	}
}
