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

declare(strict_types=1);

namespace LolaCore\Hub;

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Required for core functionality, dynamic queries, and performance. Validated inputs.

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

use WP_REST_Request;
use WP_REST_Response;

/**
 * Class DiscoverEndpoint
 *
 * Public REST endpoint that returns minimal, non-sensitive metadata
 * about this LolaCore installation. Designed for future Hub Pro
 * service discovery — no authentication required.
 *
 * Route: GET /wp-json/lolacore/v1/discover
 */
class DiscoverEndpoint
{
    /**
     * Register the REST route on the rest_api_init action.
     */
    public function register(): void
    {
        \add_action('rest_api_init', [$this, 'registerRoute']);
    }

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

    /**
     * Handle the discover request.
     *
     * Returns only public, non-sensitive metadata:
     * - lolacore flag
     * - plugin version
     * - node_id (UUID generated at activation)
     * - WordPress version
     * - hub_connection status
     *
     * @param WP_REST_Request $request The incoming request.
     * @return WP_REST_Response
     */
    public function handle(WP_REST_Request $request): WP_REST_Response
    {
        global $wp_version;

        $nodeId           = $this->getConfigValue('hub_node_id', '');
        $connectionStatus = $this->getConfigValue('hub_connection_status', 'disconnected');

        $data = [
            'lolacore'       => true,
            'version'        => defined('LOLACORE_VERSION') ? LOLACORE_VERSION : '0.0.0',
            'node_id'        => $nodeId,
            'wp_version'     => $wp_version,
            'hub_connection' => $connectionStatus,
        ];

        return new WP_REST_Response($data, 200);
    }

    /**
     * Retrieve a value from the lolacore_config table.
     *
     * @param string      $key     The config key.
     * @param string|null $default Default value if key not found.
     * @return string|null
     */
    private function getConfigValue(string $key, ?string $default = null): ?string
    {
        global $wpdb;
        $table = $wpdb->prefix . 'lolacore_config';

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Custom LolaCore table query.
        $value = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT config_value FROM {$table} WHERE config_key = %s",
                $key,
            )
        );

        return $value ?? $default;
    }
}