#include <softbus_opcua/UaServerEngine.h>

#include <softbus_core/logging/Logger.h>

#if SOFTBUS_HAS_OPCUA
#include <open62541/server.h>
#include <open62541/server_config_default.h>
#endif

namespace softbus::opcua {

UaServerEngine::UaServerEngine() = default;

UaServerEngine::~UaServerEngine()
{
    stop();
}

bool UaServerEngine::start(uint16_t port, const std::string& applicationName, const SecurityConfig& security)
{
#if !SOFTBUS_HAS_OPCUA
    (void)port;
    (void)applicationName;
    (void)security;
    SB_LOG_ERROR("UaServerEngine", "OPC UA support not built in");
    return false;
#else
    security_ = security;
    if (security.enableTls) {
        SB_LOG_WARN("UaServerEngine",
            "TLS/mTLS requested but not enabled in Phase1 build");
    }

    server_ = UA_Server_new();
    UA_ServerConfig* config = UA_Server_getConfig(server_);
    UA_StatusCode status = UA_ServerConfig_setMinimal(config, port, nullptr);
    if (status != UA_STATUSCODE_GOOD) {
        SB_LOG_ERROR("UaServerEngine", "Failed to configure server");
        UA_Server_delete(server_);
        server_ = nullptr;
        return false;
    }

    config->applicationDescription.applicationName = UA_LOCALIZEDTEXT_ALLOC("en-US", applicationName.c_str());
    status = UA_Server_run_startup(server_);
    if (status != UA_STATUSCODE_GOOD) {
        SB_LOG_ERROR("UaServerEngine", "Failed to start server");
        UA_Server_delete(server_);
        server_ = nullptr;
        return false;
    }

    running_ = true;
    SB_LOG_INFO("UaServerEngine", "OPC UA server started on port ", port);
    return true;
#endif
}

void UaServerEngine::stop()
{
#if SOFTBUS_HAS_OPCUA
    if (server_) {
        UA_Server_run_shutdown(server_);
        UA_Server_delete(server_);
        server_ = nullptr;
    }
#endif
    running_ = false;
}

void UaServerEngine::iterate()
{
#if SOFTBUS_HAS_OPCUA
    if (server_ && running_) {
        UA_Server_run_iterate(server_, false);
    }
#endif
}

} // namespace softbus::opcua
