<?php
/**
 * @package Hafenstudios\Kurato
 */

namespace Hafenstudios\Kurato\Cockpit\Rest;

use Hafenstudios\Kurato\Cockpit\Diagnostics;

defined( 'ABSPATH' ) || exit;

/**
 * GET kurato-cockpit/v1/diagnose - Verbindungsdiagnose fuer den
 * Einrichtungsassistenten. Nur der Inhaber (hs_manage_settings, Cookie-Auth im
 * wp-admin) darf sie abrufen.
 */
final class DiagnoseController {

	public const REST_NAMESPACE = 'kurato-cockpit/v1';

	private Diagnostics $diagnostics;

	/**
	 * @param Diagnostics $diagnostics Diagnose-Dienst.
	 */
	public function __construct( Diagnostics $diagnostics ) {
		$this->diagnostics = $diagnostics;
	}

	/**
	 * @return void
	 */
	public function register_routes(): void {
		register_rest_route(
			self::REST_NAMESPACE,
			'/diagnose',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'diagnose' ),
				'permission_callback' => static function () {
					if ( current_user_can( 'hs_manage_settings' ) ) {
						return true;
					}
					return new \WP_Error(
						'kurato_forbidden',
						__( 'Nur der Inhaber darf die Diagnose abrufen.', 'kurato' ),
						array( 'status' => rest_authorization_required_code() )
					);
				},
			)
		);
	}

	/**
	 * @return \WP_REST_Response
	 */
	public function diagnose(): \WP_REST_Response {
		return new \WP_REST_Response(
			array(
				'ok'     => true,
				'checks' => $this->diagnostics->collect(),
			),
			200
		);
	}
}
