#include "heart_payload.h"
#include "device_nvs.h"
#include "betteryread.h"
#include "cJSON.h"
#include "sdkconfig.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static char *heart_payload_build(int message_type, cJSON *body)
{
    if (!body) {
        return NULL;
    }

    cJSON *root = cJSON_CreateObject();
    cJSON *head = cJSON_CreateObject();
    if (!root || !head) {
        cJSON_Delete(root);
        cJSON_Delete(head);
        cJSON_Delete(body);
        return NULL;
    }

    cJSON_AddNumberToObject(head, "message_type", message_type);
    cJSON_AddItemToObject(root, "head", head);
    cJSON_AddItemToObject(root, "body", body);

    char *out = cJSON_PrintUnformatted(root);
    cJSON_Delete(root);
    return out;
}

char *heart_payload_json_malloc(const char *device_id, const char *sta_ip, bool include_ip)
{
    cJSON *body = cJSON_CreateObject();
    if (!body) {
        return NULL;
    }

    if (include_ip) {
        const char *ip = (sta_ip != NULL && sta_ip[0] != '\0') ? sta_ip : "0.0.0.0";
        cJSON_AddStringToObject(body, "ip", ip);
    }

    const char *dev = device_id_plain(device_id);

    char voltage_s[16];
    snprintf(voltage_s, sizeof(voltage_s), "%.2f", get_voltage_v());
    cJSON_AddStringToObject(body, "voltage", voltage_s);
    cJSON_AddStringToObject(body, "device_ID", dev);
    cJSON_AddStringToObject(body, "version", CONFIG_MY_APP_VERSION);

    return heart_payload_build(HEART_MSG_TYPE_HEARTBEAT, body);
}

char *heart_payload_alert_json_malloc(int message_type, const char *msg)
{
    if (msg == NULL) {
        return NULL;
    }
    if (message_type != HEART_MSG_TYPE_LOG_WARN && message_type != HEART_MSG_TYPE_LOG_ERROR) {
        return NULL;
    }

    cJSON *body = cJSON_CreateObject();
    if (!body) {
        return NULL;
    }
    cJSON_AddStringToObject(body, "msg", msg);
    return heart_payload_build(message_type, body);
}
