#include <string.h>
#include "esp_log.h"
#include "nvs_flash.h"
#include "eeprom_tls.h"

static const char *TAG = "EEPROM_TLS";

// --- Inicializa NVS ---
esp_err_t eeprom_tls_init(void) {
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        err = nvs_flash_init();
    }
    return err;
}

// --- Grava certificado PEM ---
esp_err_t eeprom_tls_write_cert(const char *cert_pem) {
    if (!cert_pem) return ESP_ERR_INVALID_ARG;

    nvs_handle_t nvs;
    esp_err_t err = nvs_open("storage", NVS_READWRITE, &nvs);
    if (err != ESP_OK) return err;

    err = nvs_set_blob(nvs, "tls_cert", cert_pem, strlen(cert_pem) + 1);
    if (err == ESP_OK) {
        nvs_commit(nvs);
        ESP_LOGI(TAG, "💾 Certificado TLS gravado na EEPROM (%d bytes)", strlen(cert_pem));
    }
    nvs_close(nvs);
    return err;
}

// --- Lê certificado PEM ---
esp_err_t eeprom_tls_read_cert(char *buffer, size_t buf_size) {
    nvs_handle_t nvs;
    esp_err_t err = nvs_open("storage", NVS_READONLY, &nvs);
    if (err != ESP_OK) return err;

    size_t required = buf_size;
    err = nvs_get_blob(nvs, "tls_cert", buffer, &required);
    nvs_close(nvs);

    if (err == ESP_OK) {
        ESP_LOGI(TAG, "📦 Certificado TLS lido (%d bytes)", (int)required);
    } else if (err == ESP_ERR_NVS_NOT_FOUND) {
        ESP_LOGW(TAG, "⚠️ Nenhum certificado TLS encontrado na EEPROM");
    } else {
        ESP_LOGE(TAG, "❌ Erro ao ler certificado (%s)", esp_err_to_name(err));
    }
    return err;
}

// --- Apaga certificado ---
esp_err_t eeprom_tls_clear_cert(void) {
    nvs_handle_t nvs;
    esp_err_t err = nvs_open("storage", NVS_READWRITE, &nvs);
    if (err != ESP_OK) return err;

    err = nvs_erase_key(nvs, "tls_cert");
    nvs_commit(nvs);
    nvs_close(nvs);

    ESP_LOGW(TAG, "🧹 Certificado TLS removido da EEPROM");
    return err;
}
