// =========================
// evse_settings_api.c
// =========================
#include "evse_settings_api.h"
#include "evse_api.h"
#include "evse_config.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, "currentLimit", evse_get_max_charging_current());
    cJSON_AddNumberToObject(config, "temperatureLimit", evse_get_temp_threshold());
    const char *json_str = cJSON_Print(config);
    httpd_resp_sendstr(req, json_str);
    free((void *)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 (current) evse_set_max_charging_current(current->valueint);
    cJSON *temp = cJSON_GetObjectItem(json, "temperatureLimit");
    if (temp) evse_set_temp_threshold(temp->valueint);

    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);
}
