<?php
/**
 * WordPress REST Routes
 *
 * Provides REST endpoints for WordPress-native data lookups
 * used by dynamic select fields in the workflow builder.
 *
 * @package Sequensy\Integrations\WordPress
 * @since 1.0.0
 */

declare(strict_types=1);

namespace Sequensy\Integrations\WordPress\Rest;

use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Class WordPressRoutes
 *
 * Registers WordPress data REST routes for dynamic field lookups.
 */
class WordPressRoutes {

	/**
	 * REST namespace.
	 *
	 * @var string
	 */
	private string $namespace = 'sequensy/v1';

	/**
	 * Register REST API routes.
	 *
	 * @return void
	 */
	public function register_routes(): void {
		register_rest_route(
			$this->namespace,
			'/wordpress/users',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_users' ),
					'permission_callback' => array( $this, 'permissions_check' ),
				),
			)
		);
	}

	/**
	 * Check permissions for REST API requests.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return bool|WP_Error True if allowed, WP_Error otherwise.
	 */
	public function permissions_check( WP_REST_Request $request ): bool|WP_Error {
		if ( ! current_user_can( 'manage_options' ) ) {
			return new WP_Error(
				'rest_forbidden',
				esc_html__( 'You do not have permission to access this resource.', 'sequensy' ),
				array( 'status' => 403 )
			);
		}

		return true;
	}

	/**
	 * Get WordPress users eligible to be post authors.
	 *
	 * @param WP_REST_Request $request Full data about the request.
	 * @return WP_REST_Response List of users with id and display_name.
	 */
	public function get_users( WP_REST_Request $request ): WP_REST_Response {
		$users = get_users(
			array(
				'capability' => 'edit_posts',
				'orderby'    => 'display_name',
				'order'      => 'ASC',
				'fields'     => array( 'ID', 'display_name' ),
			)
		);

		$result = array_map(
			function ( $user ) {
				return array(
					'id'           => (int) $user->ID,
					'display_name' => $user->display_name,
				);
			},
			$users
		);

		return rest_ensure_response( array_values( $result ) );
	}
}
