// =========================
// evse_settings_api.c
// =========================
#include "evse_settings_api.h"
#include "evse_api.h"
#include "evse_config.h"
#include "evse_limits.h"
#include "esp_log.h"
#include "cJSON.h"

static const char *TAG = "evse_settings_api";

static esp_err_t config_settings_get_handler(httpd_req_t *req) {
    httpd_resp_set_type(req, "application/json");

    cJSON *config = cJSON_CreateObject();
    cJSON_AddNumberToObject(config, "maxCurrentLimit", evse_get_max_charging_current());
    cJSON_AddNumberToObject(config, "currentLimit", evse_get_charging_current());
    cJSON_AddNumberToObject(config, "powerLimit", 0);
    cJSON_AddNumberToObject(config, "energyLimit", evse_get_consumption_limit());
    cJSON_AddNumberToObject(config, "chargingTimeLimit", evse_get_charging_time_limit());
    cJSON_AddNumberToObject(config, "temperatureLimit", evse_get_temp_threshold());

    cJSON *security = cJSON_CreateObject();
    cJSON_AddBoolToObject(security, "earthFault", false);
    cJSON_AddBoolToObject(security, "rcm", false);
    cJSON_AddItemToObject(config, "security", security);

    char *json_str = cJSON_PrintUnformatted(config);
    httpd_resp_sendstr(req, json_str ? json_str : "{}");
    if (json_str) free(json_str);
    cJSON_Delete(config);
    return ESP_OK;
}

static esp_err_t config_settings_post_handler(httpd_req_t *req) {
    char buf[512];
    int len = httpd_req_recv(req, buf, sizeof(buf) - 1);
    if (len <= 0) {
        httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Empty body");
        return ESP_FAIL;
    }
    buf[len] = '\0';
    cJSON *json = cJSON_Parse(buf);
    if (!json) {
        httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid JSON");
        return ESP_FAIL;
    }

    cJSON *current = cJSON_GetObjectItem(json, "currentLimit");
    if (cJSON_IsNumber(current)) {
        int value = current->valueint;
        int hw_max = evse_get_max_charging_current();
        if (value < 0) value = 0;
        if (value > hw_max) value = hw_max;
        evse_set_charging_current(value);
    }

    cJSON *temp = cJSON_GetObjectItem(json, "temperatureLimit");
    if (cJSON_IsNumber(temp)) {
        evse_set_temp_threshold(temp->valueint);
    }

    // Campos aceites por compatibilidade de contrato v1.
    // Nesta sprint são ignorados caso o firmware ainda não os suporte internamente.
    (void)cJSON_GetObjectItem(json, "powerLimit");
    (void)cJSON_GetObjectItem(json, "energyLimit");
    (void)cJSON_GetObjectItem(json, "chargingTimeLimit");
    (void)cJSON_GetObjectItem(json, "security");

    cJSON_Delete(json);
    httpd_resp_sendstr(req, "Configurações atualizadas com sucesso");
    return ESP_OK;
}

void register_evse_settings_handlers(httpd_handle_t server, void *ctx) {
    httpd_uri_t get_uri = {
        .uri = "/api/v1/config/settings",
        .method = HTTP_GET,
        .handler = config_settings_get_handler,
        .user_ctx = ctx
    };
    httpd_register_uri_handler(server, &get_uri);

    httpd_uri_t post_uri = {
        .uri = "/api/v1/config/settings",
        .method = HTTP_POST,
        .handler = config_settings_post_handler,
        .user_ctx = ctx
    };
    httpd_register_uri_handler(server, &post_uri);
}
