<?php
/**
 * Verification REST controller.
 *
 * @package Carticy\Conversions\Rest
 */

declare(strict_types=1);

namespace Carticy\Conversions\Rest;

use Carticy\Conversions\Diagnostics\VerificationStatus;

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

/**
 * Exposes the test-purchase verification state. The status is read from real
 * delivery evidence (a recorded purchase event / an accepted server send) - the
 * green check is never fabricated. The run action kicks the dispatch queue so a
 * pending server send is attempted, then reports the (still real) evidence.
 */
final class VerificationController extends AbstractRestController {

	/**
	 * Verification evidence evaluator.
	 *
	 * @var VerificationStatus
	 */
	private VerificationStatus $verification;

	/**
	 * Premium server bridge.
	 *
	 * @var PremiumServerBridge
	 */
	private PremiumServerBridge $server;

	/**
	 * Constructor.
	 *
	 * @param VerificationStatus  $verification Verification evidence evaluator.
	 * @param PremiumServerBridge $server Premium server bridge.
	 */
	public function __construct( VerificationStatus $verification, PremiumServerBridge $server ) {
		$this->verification = $verification;
		$this->server       = $server;
	}

	/**
	 * Declared routes.
	 *
	 * @return array<int, array<string, mixed>>
	 */
	public function routes(): array {
		return array(
			array(
				'methods'  => 'GET',
				'route'    => '/verification',
				'callback' => array( $this, 'get_status' ),
			),
			array(
				'methods'  => 'POST',
				'route'    => '/verification/run',
				'callback' => array( $this, 'run' ),
			),
		);
	}

	/**
	 * Read the verification evidence.
	 *
	 * @return \WP_REST_Response
	 */
	public function get_status(): \WP_REST_Response {
		return $this->ok( $this->verification->evaluate() );
	}

	/**
	 * Kick the queue (server) and re-report the evidence.
	 *
	 * @return \WP_REST_Response
	 */
	public function run(): \WP_REST_Response {
		// Re-checking is the only honest action: a queued server send is nudged
		// to run, but the reported state is still derived from real evidence.
		$this->server->kick_queue();

		return $this->get_status();
	}
}
