#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>
#include "esp_log.h"
#include "mqtt_client.h"
#include "cJSON.h"
#include "eeprom_virtual.h"

static const char *TAG = "MQTT_CMD";
extern esp_mqtt_client_handle_t mqtt_client;

#define TOPIC_RESP "esp/esp32-002/resp"

void mqtt_comandos_handle(cJSON *root) {
    cJSON *id = cJSON_GetObjectItem(root, "id");
    cJSON *cmd = cJSON_GetObjectItem(root, "cmd");
    if (!cJSON_IsNumber(id) || !cJSON_IsString(cmd)) {
        ESP_LOGW(TAG, "⚠️ Comando inválido");
        return;
    }

    int req_id = id->valueint;
    const char *comando = cmd->valuestring;

    // -------- FS_LIST --------
    if (strcmp(comando, "FS_LIST") == 0) {
        DIR *dir = opendir("/spiffs");
        if (!dir) {
            char resp[128];
            snprintf(resp, sizeof(resp), "{\"id\":%d,\"error\":\"fs_not_mounted\"}", req_id);
            esp_mqtt_client_publish(mqtt_client, TOPIC_RESP, resp, 0, 1, false);
            return;
        }

        char json[2048];
        snprintf(json, sizeof(json), "{\"id\":%d,\"files\":[", req_id);

        struct dirent *entry;
        int first = 1;
        while ((entry = readdir(dir)) != NULL) {
            char path[512];
            snprintf(path, sizeof(path), "/spiffs/%.255s", entry->d_name);
            struct stat st;
            if (stat(path, &st) == 0) {
                // 🔧 Correção: buffer maior e limite de nome seguro
                char file_json[320];
                snprintf(file_json, sizeof(file_json),
                         "{\"name\":\"%.200s\",\"size\":%ld}", entry->d_name, (long)st.st_size);
                if (!first) strlcat(json, ",", sizeof(json));
                strlcat(json, file_json, sizeof(json));
                first = 0;
            }
        }
        closedir(dir);
        strlcat(json, "]}", sizeof(json));
        esp_mqtt_client_publish(mqtt_client, TOPIC_RESP, json, 0, 1, false);
    }

    // -------- CERT_REQ --------
    else if (strcmp(comando, "CERT_REQ") == 0) {
        char json[128];
        snprintf(json, sizeof(json), "{\"id\":%d,\"cmd\":\"CERT_REQ\"}", req_id);
        esp_mqtt_client_publish(mqtt_client, TOPIC_RESP, json, 0, 1, false);
        ESP_LOGI(TAG, "📤 Pedido de certificado enviado");

    // -------- CERT_SAVE --------
    } else if (strcmp(comando, "CERT_SAVE") == 0) {
        cJSON *cert = cJSON_GetObjectItem(root, "cert");
        if (!cJSON_IsString(cert)) {
            char resp[128];
            snprintf(resp, sizeof(resp), "{\"id\":%d,\"error\":\"missing_cert\"}", req_id);
            esp_mqtt_client_publish(mqtt_client, TOPIC_RESP, resp, 0, 1, false);
            return;
        }

        const char *cert_str = cert->valuestring;

        // 🔧 Correção: usar versão binária (string + terminador)
        if (eeprom_virtual_write_bin("cert", cert_str, strlen(cert_str) + 1) == ESP_OK) {
            ESP_LOGI(TAG, "💾 Certificado gravado na EEPROM (%d bytes)", (int)strlen(cert_str));
            char resp[128];
            snprintf(resp, sizeof(resp), "{\"id\":%d,\"cmd\":\"CERT_SAVE\",\"ok\":true}", req_id);
            esp_mqtt_client_publish(mqtt_client, TOPIC_RESP, resp, 0, 1, false);
        } else {
            ESP_LOGE(TAG, "❌ Falha ao gravar certificado");
        }
    }
}
