<?php
/**
 * SiteKeyReceiver - Public site key endpoint for pre-activation proof-of-possession.
 *
 * Exposes the stable Ed25519 public key derived from the SecurWP key.
 * The Console uses this to verify that activation requests are signed by the real website.
 *
 */
declare(strict_types=1);

namespace SecurWP\Modules\Scanner\API;

use SecurWP\Includes\SecurWPKeyManager;

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

class SiteKeyReceiver {

    public const NAMESPACE = 'securwp/v1';

    /**
     * Register REST API routes.
     *
     * @return void
     */
    public static function register(): void {
        add_action( 'rest_api_init', [ __CLASS__, 'register_routes' ] );
    }

    /**
     * Register the site-key endpoint (public).
     *
     * @return void
     */
    public static function register_routes(): void {
        register_rest_route( self::NAMESPACE, '/site-key', [
            'methods'             => 'GET',
            'callback'            => [ __CLASS__, 'get_site_key' ],
            'permission_callback' => '__return_true',
        ] );
    }

    /**
     * Return the public key as base64url.
     *
     * @param \WP_REST_Request $request
     * @return \WP_REST_Response
     */
    public static function get_site_key( $request ) {
        $public = SecurWPKeyManager::get_site_public_key_b64();
        if ( $public === '' ) {
            return new \WP_REST_Response(
                [
                    'ok' => false,
                    'error' => 'site_key_unavailable',
                ],
                500
            );
        }

        // Fingerprint is informational only.
        $raw = base64_decode( strtr( $public, '-_', '+/' ) . '==', true );
        $fp = is_string( $raw ) ? hash( 'sha256', $raw ) : '';

        return new \WP_REST_Response(
            [
                'ok' => true,
                'public_key' => $public,
                'fingerprint' => $fp,
            ],
            200
        );
    }
}

