<?php
/**
 * REST — site global design tokens.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\REST;

use AuraBuilder\Globals\SiteGlobals;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

final class GlobalsController {

	public function register( string $ns ): void {
		register_rest_route(
			$ns,
			'/globals',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_item' ),
					'permission_callback' => array( $this, 'can_edit' ),
				),
				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_item' ),
					'permission_callback' => array( $this, 'can_edit' ),
				),
			)
		);
	}

	/**
	 * Site-wide design tokens — same audience as Theme Builder (admin / page editors).
	 */
	public function can_edit(): bool {
		return \AuraBuilder\Support\Capabilities::can_edit_theme_parts();
	}

	public function get_item(): WP_REST_Response {
		return new WP_REST_Response(
			array(
				'ok'      => true,
				'globals' => SiteGlobals::get(),
				'css'     => SiteGlobals::css(),
			)
		);
	}

	/**
	 * @return WP_REST_Response|WP_Error
	 */
	public function update_item( WP_REST_Request $req ) {
		$body = $req->get_json_params();
		if ( ! is_array( $body ) ) {
			return new WP_Error( 'ab_invalid', 'Payload inválido', array( 'status' => 400 ) );
		}
		// Accept { globals: {...} } or flat body.
		$data = is_array( $body['globals'] ?? null ) ? $body['globals'] : $body;
		$saved = SiteGlobals::save( $data );
		return new WP_REST_Response(
			array(
				'ok'      => true,
				'globals' => $saved,
				'css'     => SiteGlobals::css(),
			)
		);
	}
}
