<?php
/**
 * Custom Fields meta key resolution and collision detection.
 *
 * @package CustomFields
 * @since 1.2.0
 */

namespace CustomFields;

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

/**
 * Resolves stored meta keys and checks for global collisions.
 */
final class MetaKeys {

	/**
	 * Resolve the database meta key for a field within a group.
	 *
	 * @param string               $group_key Unused; kept for call-site compatibility.
	 * @param array<string, mixed> $field     Field definition.
	 */
	public static function resolve( string $group_key, array $field ): string {
		unset( $group_key );

		$name = (string) ( $field['name'] ?? '' );
		if ( $name !== '' ) {
			return $name;
		}

		return (string) ( $field['key'] ?? '' );
	}

	/**
	 * Collect resolved meta keys from every stored group.
	 *
	 * @param Storage     $storage       Storage instance.
	 * @param string|null $exclude_group Skip this group key (used when editing).
	 * @return array<string, string> meta_key => group_key
	 */
	public static function registeredKeys( Storage $storage, ?string $exclude_group = null ): array {
		$map = [];
		foreach ( $storage->all() as $group_key => $group ) {
			if ( ! is_array( $group ) ) {
				continue;
			}
			if ( $exclude_group !== null && (string) $group_key === $exclude_group ) {
				continue;
			}

			$fields = isset( $group['fields'] ) && is_array( $group['fields'] ) ? $group['fields'] : [];
			foreach ( $fields as $field ) {
				if ( ! is_array( $field ) ) {
					continue;
				}
				$type = (string) ( $field['type'] ?? 'text' );
				if ( ! Config::storesValue( $type ) ) {
					continue;
				}
				$meta_key = self::resolve( (string) $group_key, $field );
				if ( $meta_key !== '' ) {
					$map[ $meta_key ] = (string) $group_key;
				}
			}
		}

		return $map;
	}
}
