/**************************************************************************/
/*  aethex_cloud.h                                                        */
/**************************************************************************/
/*                       AeThex Engine                                    */
/*                    https://aethex.dev                                  */
/**************************************************************************/

#ifndef AETHEX_CLOUD_H
#define AETHEX_CLOUD_H

#include "core/object/ref_counted.h"
#include "core/io/http_client.h"
#include "modules/websocket/websocket_peer.h"

class AethexAuth;
class AethexCloudSave;
class AethexAssetLibrary;
class AethexTelemetry;

class AethexCloud : public Object {
    GDCLASS(AethexCloud, Object);

public:
    enum ConnectionStatus {
        STATUS_DISCONNECTED,
        STATUS_CONNECTING,
        STATUS_CONNECTED,
        STATUS_ERROR
    };

private:
    static AethexCloud *singleton;

    String gateway_url;
    String api_key;
    String auth_token;
    ConnectionStatus status = STATUS_DISCONNECTED;

    Ref<AethexAuth> auth;
    Ref<AethexCloudSave> cloud_save;
    Ref<AethexAssetLibrary> asset_library;
    Ref<AethexTelemetry> telemetry;

    Ref<WebSocketPeer> websocket;
    bool websocket_connected = false;

    // Internal methods
    void _websocket_connect();
    void _websocket_process();
    void _on_websocket_message(const PackedByteArray &p_data);

protected:
    static void _bind_methods();

public:
    static AethexCloud *get_singleton();

    // Configuration
    void set_gateway_url(const String &p_url);
    String get_gateway_url() const;

    void set_api_key(const String &p_key);
    String get_api_key() const;

    // Connection
    Error connect_to_gateway();
    void disconnect_from_gateway();
    ConnectionStatus get_status() const;
    bool is_connected() const;

    // Auth token (set after login)
    void set_auth_token(const String &p_token);
    String get_auth_token() const;

    // Sub-services
    Ref<AethexAuth> get_auth() const;
    Ref<AethexCloudSave> get_cloud_save() const;
    Ref<AethexAssetLibrary> get_asset_library() const;
    Ref<AethexTelemetry> get_telemetry() const;

    // HTTP helpers
    Dictionary make_request(const String &p_endpoint, HTTPClient::Method p_method = HTTPClient::METHOD_GET, const Dictionary &p_data = Dictionary());
    void make_request_async(const String &p_endpoint, HTTPClient::Method p_method = HTTPClient::METHOD_GET, const Dictionary &p_data = Dictionary(), const Callable &p_callback = Callable());

    // Process (call from main loop)
    void process(double p_delta);

    AethexCloud();
    ~AethexCloud();
};

VARIANT_ENUM_CAST(AethexCloud::ConnectionStatus);

#endif // AETHEX_CLOUD_H
