<?php
/**
 * Field Catalog REST API.
 *
 * @package JOCBM
 *
 * Copyright (C) 2026 JayOnCode
 * License: GPL-2.0-or-later
 */

namespace JOCBM\Rest;

use JOCBM\Services\FieldCatalog;
use WP_REST_Response;
use WP_REST_Server;

defined( 'ABSPATH' ) || exit;

/**
 * Exposes Field Catalog presets for tooling / Pro (not My Blocks end-user UI).
 */
final class FieldCatalogController {

	use RestPermissions;

	/**
	 * Register routes.
	 */
	public function register_routes(): void {
		register_rest_route(
			RestApi::NAMESPACE,
			'/field-catalog',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'index' ),
				'permission_callback' => array( $this, 'can_manage' ),
			)
		);
	}

	/**
	 * List catalog presets with expanded field definitions.
	 *
	 * @return WP_REST_Response
	 */
	public function index(): WP_REST_Response {
		$items = array();
		foreach ( FieldCatalog::ids() as $id ) {
			$fields = FieldCatalog::compose(
				array(
					array(
						'$field' => $id,
					),
				)
			);
			if ( empty( $fields ) ) {
				continue;
			}

			$keys  = array();
			$label = '';
			foreach ( $fields as $field ) {
				if ( ! is_array( $field ) ) {
					continue;
				}
				$key = (string) ( $field['key'] ?? '' );
				if ( '' !== $key ) {
					$keys[] = $key;
				}
				if ( '' === $label && ! empty( $field['label'] ) ) {
					$label = (string) $field['label'];
				}
			}
			if ( '' === $label ) {
				$label = self::humanize_id( $id );
			}

			$items[] = array(
				'id'     => $id,
				'label'  => $label,
				'keys'   => $keys,
				'fields' => $fields,
			);
		}

		return new WP_REST_Response(
			array(
				'items' => $items,
			),
			200
		);
	}

	/**
	 * @param string $id Preset id.
	 */
	private static function humanize_id( string $id ): string {
		$id = str_replace( array( '.', '-', '_' ), ' ', $id );
		return ucwords( trim( $id ) );
	}
}
