#include "tcp_ssl_password.hpp"

#include <openssl/md5.h>
#include <sstream>
#include <iomanip>

namespace netcore {

static std::string md5_hex(const std::string& input) {
    MD5_CTX ctx;
    MD5_Init(&ctx);
    MD5_Update(&ctx, input.data(), input.size());

    unsigned char digest[MD5_DIGEST_LENGTH];
    MD5_Final(digest, &ctx);

    std::ostringstream oss;
    oss << std::hex << std::setfill('0');
    for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
        oss << std::setw(2) << static_cast<unsigned int>(digest[i]);
    }
    return oss.str();
}

std::string calculate_tcp_ssl_password(const std::string& device_id, const std::string& iccid) {
    std::string md5_device_hex = md5_hex(device_id);
    if (!iccid.empty()) {
        md5_device_hex += iccid;
    }
    return md5_hex(md5_device_hex);
}

} // namespace netcore
