<?php
/**
 * REST endpoints for Wuppi settings (consumed by the admin SPA).
 *
 * @package wuppi
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Register the /wuppi/v1/settings route.
 */
function wuppi_register_rest_settings_routes() {
	register_rest_route(
		'wuppi/v1',
		'/settings',
		array(
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => 'wuppi_rest_get_settings',
				'permission_callback' => 'wuppi_rest_settings_permission',
			),
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => 'wuppi_rest_save_settings',
				'permission_callback' => 'wuppi_rest_settings_permission',
				'args'                => array(
					'settings' => array(
						'type'     => 'object',
						'required' => true,
					),
				),
			),
		)
	);
}
add_action( 'rest_api_init', 'wuppi_register_rest_settings_routes' );

/**
 * Capability check for the REST endpoints.
 *
 * @return bool
 */
function wuppi_rest_settings_permission() {
	return current_user_can( wuppi_get_settings_page_capability() );
}

/**
 * GET handler — returns current settings + defaults so the SPA can hydrate.
 *
 * @return WP_REST_Response
 */
function wuppi_rest_get_settings() {
	return rest_ensure_response(
		array(
			'settings' => wuppi_get_settings(),
			'defaults' => wuppi_get_settings_defaults(),
		)
	);
}

/**
 * POST handler — sanitizes and saves settings, returns the sanitized values.
 *
 * @param WP_REST_Request $request Incoming request.
 * @return WP_REST_Response|WP_Error
 */
function wuppi_rest_save_settings( WP_REST_Request $request ) {
	$payload = $request->get_param( 'settings' );

	if ( ! is_array( $payload ) ) {
		return new WP_Error( 'wuppi_invalid_settings', __( 'Settings payload must be an object.', 'wuppi' ), array( 'status' => 400 ) );
	}

	$sanitized = wuppi_sanitize_settings( $payload );
	update_option( 'wuppi_settings', $sanitized );

	return rest_ensure_response(
		array(
			'settings' => $sanitized,
			'saved'    => true,
		)
	);
}
