#include "evse_link.h"
#include "evse_link_config_api.h"   // new header for these handlers
#include "esp_log.h"
#include "cJSON.h"

static const char *TAG = "link_config_api";

// GET /api/v1/config/link
static esp_err_t link_config_get_handler(httpd_req_t *req) {
    bool   enabled = evse_link_is_enabled();
    uint8_t mode    = evse_link_get_mode();    // 0=MASTER,1=SLAVE
    uint8_t self_id = evse_link_get_self_id();

    ESP_LOGD(TAG, "GET link config: enabled=%d mode=%u id=%u",
             enabled, mode, self_id);

    httpd_resp_set_type(req, "application/json");
    cJSON *root = cJSON_CreateObject();
    cJSON_AddBoolToObject  (root, "linkEnabled", enabled);
    cJSON_AddStringToObject(root, "linkMode",
        mode == EVSE_LINK_MODE_MASTER ? "MASTER" : "SLAVE");
    cJSON_AddNumberToObject(root, "linkSelfId", self_id);

    char *s = cJSON_Print(root);
    httpd_resp_sendstr(req, s);
    ESP_LOGD(TAG, "  payload: %s", s);
    free(s);
    cJSON_Delete(root);
    return ESP_OK;
}

// POST /api/v1/config/link
static esp_err_t link_config_post_handler(httpd_req_t *req) {
    char buf[256];
    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';
    ESP_LOGD(TAG, "POST link config: %s", buf);

    cJSON *json = cJSON_Parse(buf);
    if (!json) {
        httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid JSON");
        return ESP_FAIL;
    }

    // linkEnabled
    cJSON *j_en = cJSON_GetObjectItem(json, "linkEnabled");
    if (j_en && cJSON_IsBool(j_en)) {
        evse_link_set_enabled(cJSON_IsTrue(j_en));
        ESP_LOGD(TAG, "  set enabled = %d", cJSON_IsTrue(j_en));
    }

    // linkMode
    cJSON *j_md = cJSON_GetObjectItem(json, "linkMode");
    if (j_md && cJSON_IsString(j_md)) {
        const char *m = j_md->valuestring;
        if (strcmp(m, "MASTER") == 0) {
            evse_link_set_mode(EVSE_LINK_MODE_MASTER);
        } else if (strcmp(m, "SLAVE") == 0) {
            evse_link_set_mode(EVSE_LINK_MODE_SLAVE);
        } else {
            cJSON_Delete(json);
            httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST,
                                "Invalid linkMode (must be MASTER or SLAVE)");
            return ESP_FAIL;
        }
        ESP_LOGD(TAG, "  set mode = %s", m);
    }

    // linkSelfId
    cJSON *j_id = cJSON_GetObjectItem(json, "linkSelfId");
    if (j_id && cJSON_IsNumber(j_id)) {
        int id = j_id->valueint;
        if (id < 0 || id > 254) {
            cJSON_Delete(json);
            httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST,
                                "Invalid linkSelfId (0–254)");
            return ESP_FAIL;
        }
        evse_link_set_self_id((uint8_t)id);
        ESP_LOGD(TAG, "  set self_id = %d", id);
    }

    cJSON_Delete(json);
    httpd_resp_sendstr(req, "Link settings updated");
    return ESP_OK;
}

void register_link_config_handlers(httpd_handle_t server, void *ctx) {
    httpd_uri_t get = {
        .uri      = "/api/v1/config/link",
        .method   = HTTP_GET,
        .handler  = link_config_get_handler,
        .user_ctx = ctx
    };
    httpd_register_uri_handler(server, &get);

    httpd_uri_t post = {
        .uri      = "/api/v1/config/link",
        .method   = HTTP_POST,
        .handler  = link_config_post_handler,
        .user_ctx = ctx
    };
    httpd_register_uri_handler(server, &post);
}
