<?php
/**
 * Widget catalog endpoint for the editor.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\REST;

use AuraBuilder\Widgets\WidgetRegistry;
use WP_REST_Response;
use WP_REST_Server;

final class WidgetsController {

	public function register( string $ns ): void {
		register_rest_route(
			$ns,
			'/widgets',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'list_widgets' ),
				'permission_callback' => static fn() => current_user_can( 'edit_posts' ),
			)
		);
	}

	public function list_widgets(): WP_REST_Response {
		return new WP_REST_Response(
			array(
				'widgets' => WidgetRegistry::instance()->catalog(),
			)
		);
	}
}
