<?php

/**
 * LolaCore — Hub Discover Endpoint
 *
 * @package LolaCore
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\Hub;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use WP_REST_Request;
use WP_REST_Response;

/**
 * Class DiscoverEndpoint
 *
 * Minimal, non-sensitive metadata about this LolaCore node, for a LolaHub
 * master to identify the site during and after pairing (sprint C0).
 *
 * Returns: lolacore flag, plugin version, stable node_id, WordPress
 * version, and the current master connection state. Never returns
 * credentials, provider keys, or any other secret.
 *
 * Route: GET /wp-json/lolacore/v1/pairing/discover
 * Auth:  manage_options (kept until C1 defines the fleet channel auth).
 */
class DiscoverEndpoint
{
    private PairingRegistrar $pairing;

    public function __construct(?PairingRegistrar $pairing = null)
    {
        $this->pairing = $pairing ?? new PairingRegistrar();
    }

    /**
     * Register the REST route on the rest_api_init action.
     */
    public function register(): void
    {
        \add_action('rest_api_init', [$this, 'registerRoute']);
    }

    /**
     * Register the /pairing/discover route.
     */
    public function registerRoute(): void
    {
        \register_rest_route('lolacore/v1', '/pairing/discover', [
            'methods'             => \WP_REST_Server::READABLE,
            'callback'            => [$this, 'handle'],
            'permission_callback' => static function (): bool {
                return \current_user_can('manage_options');
            },
        ]);
    }

    /**
     * Handle the discover request.
     *
     * @param WP_REST_Request $request The incoming request.
     */
    public function handle(WP_REST_Request $request): WP_REST_Response
    {
        unset($request);

        global $wp_version;

        return new WP_REST_Response([
            'lolacore'   => true,
            'version'    => defined('LOLACORE_VERSION') ? LOLACORE_VERSION : '0.0.0',
            'node_id'    => $this->pairing->getNodeId(),
            'wp_version' => $wp_version,
            'connection' => $this->pairing->getConnectionState(),
        ], 200);
    }
}
