<?php
/**
 * REST endpoint for the readiness report.
 *
 * GET /wp-json/upgrade-pilot/v1/report
 *
 * Free and ungated. This lives in the free build deliberately: the payload is
 * assembled from data already on the site, so there is nothing here to sell back
 * to the site owner. It shares one schema with the WP-CLI JSON output
 * (UPilot_Report::shape), so a fleet dashboard reading either surface gets the
 * same document.
 *
 * The permission callback is a WordPress capability check, not a licence check:
 * the report describes the site's plugins and server, so it is for people who are
 * already trusted to manage them.
 *
 * @package Upgrade_Pilot
 */

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

/**
 * Class UPilot_REST
 */
class UPilot_REST {

	const NAMESPACE_V1 = 'upgrade-pilot/v1';

	/**
	 * Plugin container.
	 *
	 * @var UPilot_Plugin
	 */
	private $plugin;

	/**
	 * Constructor.
	 *
	 * @param UPilot_Plugin $plugin Plugin container.
	 */
	public function __construct( UPilot_Plugin $plugin ) {
		$this->plugin = $plugin;

		add_action( 'rest_api_init', array( $this, 'register_routes' ) );
	}

	/**
	 * Register the routes.
	 */
	public function register_routes() {
		register_rest_route(
			self::NAMESPACE_V1,
			'/report',
			array(
				'methods'             => 'GET',
				'permission_callback' => array( $this, 'can_read' ),
				'callback'            => array( $this, 'get_report' ),
			)
		);
	}

	/**
	 * Who may read the report.
	 *
	 * @return bool
	 */
	public function can_read() {
		return current_user_can( UPilot_Store::cap() );
	}

	/**
	 * The report, in the shared export schema.
	 *
	 * @return WP_REST_Response
	 */
	public function get_report() {
		return rest_ensure_response( UPilot_Report::shape( $this->plugin->get( 'report' )->get() ) );
	}
}
