import { uniqueId } from '@gravityforms/utils';

/**
 * @function augmentItems
 * @description Augment the items with unique IDs if they don't have one.
 *
 * @since 4.7.0
 *
 * @param {Array}  items   The items to augment.
 * @param {object} args    Arguments to augment items with.
 * @param {string} args.id The id prefix.
 *
 * @return {Array} The augmented items.
 */
export const augmentItems = ( items, { id: idPrefix = '' } ) => {
	return items.map( ( item ) => {
		if ( Array.isArray( item.children ) ) {
			return {
				...item,
				id: item.id ? item.id : uniqueId( idPrefix ),
				children: augmentItems( item.children, { id: idPrefix } ),
			};
		}

		if ( item.id ) {
			return item;
		}

		return {
			...item,
			id: uniqueId( idPrefix ),
		};
	} );
};
