<?php
/**
 * [1.5.211] App Version Check — endpoint REST público
 *
 * GET /1mz/v1/app/version-check?platform=android&version_code=197
 *
 * Sem autenticação — a app pode estar sem sessão activa, e este endpoint
 * é o primeiro a ser chamado no arranque.
 *
 * Resposta:
 *   {
 *     "status": "ok" | "soft_update" | "force_update" | "blocked",
 *     "latest_version": "1.6.99",
 *     "latest_version_code": 199,
 *     "min_version": "1.6.95",
 *     "min_version_code": 195,
 *     "emergency": false,
 *     "store_url": "https://play.google.com/store/apps/details?id=...",
 *     "force_message": "...",
 *     "changelog": ["✨ X", "🐛 Y"]
 *   }
 */

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

add_action( 'rest_api_init', 'rmbz_api_register_app_version_routes' );

function rmbz_api_register_app_version_routes() {
    register_rest_route( RMBZ_API_NAMESPACE, '/app/version-check', [
        'methods'             => 'GET',
        'callback'            => 'rmbz_api_handle_app_version_check',
        'permission_callback' => '__return_true', // público
        'args' => [
            'platform' => [
                'type'    => 'string',
                'default' => 'android',
            ],
            'version_code' => [
                'type'    => 'integer',
                'default' => 0,
            ],
        ],
    ] );
}

function rmbz_api_handle_app_version_check( WP_REST_Request $request ) {
    $platform     = sanitize_key( (string) $request->get_param( 'platform' ) );
    $client_code  = max( 0, (int) $request->get_param( 'version_code' ) );

    // Restringir plataformas suportadas
    if ( ! in_array( $platform, [ 'android', 'ios' ], true ) ) {
        $platform = 'android';
    }

    $response = rmbz_app_version_build_response( $client_code, $platform );

    // Sem rmbz_api_ok porque queremos resposta lean (sem envelope)
    return new WP_REST_Response( $response, 200 );
}
