<?php

namespace Storeplugin\PDFInvoice\Framework\Rest;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Framework\Abstracts\AbstractMeta;

/**
 * Register post meta REST schemas for framework metaboxes.
 */
final class PostMetaRegistrar
{
    /**
     * Register the post meta fields exposed by the provided metabox.
     *
     * @param AbstractMeta $metaBox
     * @return void
     */
    public static function register(AbstractMeta $metaBox): void
    {
        $postTypes = $metaBox->restPostTypes();
        if ($postTypes === []) {
            return;
        }

        foreach ($metaBox->restFields() as $field) {
            if (!is_array($field)) {
                continue;
            }

            $id = \sanitize_key((string) ($field['id'] ?? ''));
            if ($id === '') {
                continue;
            }

            $schema = FieldSchemaFactory::buildForField($field);
            $type = isset($schema['type']) && is_string($schema['type']) ? $schema['type'] : 'string';

            foreach ($postTypes as $postType) {
                \register_post_meta($postType, $id, [
                    'type'              => $type,
                    'description'       => $field['label'] ?? '',
                    'single'            => true,
                    'sanitize_callback' => [$metaBox, 'sanitizeRegisteredMeta'],
                    'auth_callback'     => [$metaBox, 'authorizeRegisteredMetaWrite'],
                    'show_in_rest'      => [
                        'schema' => $schema,
                    ],
                ]);
            }
        }
    }
}
