<?php
/**
 * Explicit native WordPress metadata scheduling registry.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChanges\WordPressContent;

use ScheduledChanges\Extension\PublicHooks;

/**
 * Intersects the public allowlist with WordPress registered post metadata.
 */
final class WordPressMetaFieldRegistry {
	/**
	 * @return array<string,array{registration:array<string,mixed>,options:array<string,mixed>}>
	 */
	public function allowedFor( string $post_type ): array {
		$registered = get_registered_meta_keys( 'post', $post_type );
		$allowlist  = PublicHooks::wordpressMetaFields( array(), $post_type );
		$allowed    = array();

		foreach ( $allowlist as $index => $options ) {
			$key = is_string( $index ) ? $index : ( is_scalar( $options ) ? (string) $options : '' );

			if (
				'' === $key
				|| '_' === substr( $key, 0, 1 )
				|| ! isset( $registered[ $key ] )
				|| ! is_array( $registered[ $key ] )
			) {
				continue;
			}

			$allowed[ $key ] = array(
				'registration' => $registered[ $key ],
				'options'      => is_string( $index ) && is_array( $options ) ? $options : array(),
			);
		}

		ksort( $allowed );

		return $allowed;
	}

	/**
	 * @return array{registration:array<string,mixed>,options:array<string,mixed>}|null
	 */
	public function get( string $post_type, string $key ): ?array {
		return $this->allowedFor( $post_type )[ $key ] ?? null;
	}
}
