/*
 * ============================================================
 *  Ejemplo 10 — Versiones en Tiempo Real (polling)
 *
 *  Endpoint: GET /api/version/{slug}
 *
 *  Desde el panel (Versiones) puedes crear slugs de version
 *  para cada variante de tu app y actualizarlos en caliente.
 *  Tu C++ los lee en tiempo real sin necesidad de reiniciar.
 *
 *  Casos de uso:
 *    - Verificar la version actual de multiples builds
 *    - Bloquear versiones antiguas automaticamente
 *    - Mostrar la version mas reciente en tu UI
 *    - Forzar updates sin recompilar el loader
 *
 *  El JSON del endpoint retorna:
 *    { "version": "1.2.3" }
 * ============================================================
 */
#include <string>
#include <iostream>
#include <thread>
#include <chrono>
#include <wininet.h>
#pragma comment(lib, "wininet.lib")

// ── Helper HTTP GET ──────────────────────────────────────────────────────────
std::string HttpGet(const std::string& url) {
    HINTERNET hInternet = InternetOpenA("SAO", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    if (!hInternet) return "";
    HINTERNET hUrl = InternetOpenUrlA(hInternet, url.c_str(), NULL, 0, INTERNET_FLAG_RELOAD, 0);
    if (!hUrl) { InternetCloseHandle(hInternet); return ""; }
    std::string result;
    char buf[1024];
    DWORD read = 0;
    while (InternetReadFile(hUrl, buf, sizeof(buf), &read) && read > 0)
        result.append(buf, read);
    InternetCloseHandle(hUrl);
    InternetCloseHandle(hInternet);
    return result;
}

// ── Estado global de versiones ───────────────────────────────────────────────
// Puedes tener tantos slugs como necesites.
// En este ejemplo manejamos 3 variantes: normal, max, y max-tela.
std::string g_ffNormalVersion  = "";
std::string g_ffMaxVersion     = "";
std::string g_ffTelaVersion    = "";
bool        g_versionsLoaded   = false;

// ── Extraer "version" del JSON ───────────────────────────────────────────────
static std::string extractVersion(const std::string& json) {
    auto pos = json.find("\"version\":\"");
    if (pos == std::string::npos) return "";
    pos += 11; // longitud de "version":"
    auto end = json.find("\"", pos);
    if (end == std::string::npos) return "";
    return json.substr(pos, end - pos);
}

// ── Thread de polling — corre en background ──────────────────────────────────
// Reemplaza los slugs con los que creaste en el panel (Versiones)
void FetchVersions() {
    while (true) {
        auto v1 = extractVersion(HttpGet("https://saoauth.com/api/version/ff-normal"));
        auto v2 = extractVersion(HttpGet("https://saoauth.com/api/version/ff-max"));
        auto v3 = extractVersion(HttpGet("https://saoauth.com/api/version/ff-max-tela"));

        if (!v1.empty()) g_ffNormalVersion = v1;
        if (!v2.empty()) g_ffMaxVersion    = v2;
        if (!v3.empty()) g_ffTelaVersion   = v3;

        if (!g_versionsLoaded && !v1.empty() && !v2.empty() && !v3.empty())
            g_versionsLoaded = true;

        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

// ── Ejemplo de uso ───────────────────────────────────────────────────────────
int main() {
    // Lanzar thread de polling
    std::thread(FetchVersions).detach();

    // Esperar a que carguen todas las versiones
    std::cout << "Cargando versiones...\n";
    while (!g_versionsLoaded) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

    std::cout << "[Versiones] Cargadas correctamente\n";
    std::cout << "  FF Normal   : " << g_ffNormalVersion << "\n";
    std::cout << "  FF Max      : " << g_ffMaxVersion    << "\n";
    std::cout << "  FF Max Tela : " << g_ffTelaVersion   << "\n";

    // ── Comparar con la version local para forzar update ─────────────────────
    const std::string LOCAL_VERSION = "1.0";

    if (g_ffNormalVersion != LOCAL_VERSION) {
        std::string msg = "Nueva version disponible: " + g_ffNormalVersion +
                          "\nTu version: " + LOCAL_VERSION;
        MessageBoxA(NULL, msg.c_str(), "Actualizacion requerida", MB_ICONWARNING);
        // Puedes cerrar el programa o redirigir a la descarga
    }

    // ── Monitorear cambios en tiempo real ────────────────────────────────────
    // En tu render loop puedes mostrar la version actual en tu UI:
    //   ImGui::Text("Version: %s", g_ffNormalVersion.c_str());
    //
    // Si el admin cambia la version desde el panel, tu app lo detecta
    // en ~1 segundo sin reiniciar.

    std::cout << "\nMonitoreando cambios... (Ctrl+C para salir)\n";
    std::string lastV1 = g_ffNormalVersion;
    std::string lastV2 = g_ffMaxVersion;
    std::string lastV3 = g_ffTelaVersion;

    while (true) {
        if (g_ffNormalVersion != lastV1) {
            std::cout << "[UPDATE] FF Normal: " << lastV1 << " -> " << g_ffNormalVersion << "\n";
            lastV1 = g_ffNormalVersion;
        }
        if (g_ffMaxVersion != lastV2) {
            std::cout << "[UPDATE] FF Max: " << lastV2 << " -> " << g_ffMaxVersion << "\n";
            lastV2 = g_ffMaxVersion;
        }
        if (g_ffTelaVersion != lastV3) {
            std::cout << "[UPDATE] FF Max Tela: " << lastV3 << " -> " << g_ffTelaVersion << "\n";
            lastV3 = g_ffTelaVersion;
        }

        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    return 0;
}
