#include "rest_main.h"
#include "evse_settings_api.h"
#include "meters_settings_api.h"
#include "loadbalancing_settings_api.h"
#include "evse_link_config_api.h"
#include "network_api.h"
#include "ocpp_api.h"
#include "auth_api.h"
#include "dashboard_api.h"
#include "scheduler_settings_api.h"
#include "static_file_api.h"
#include "system_api.h"
#include "esp_log.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

static const char *TAG = "rest_main";

esp_err_t rest_server_init(const char *base_path)
{
    ESP_LOGI(TAG, "Initializing REST API with base path: %s", base_path);

    rest_server_context_t *ctx = calloc(1, sizeof(rest_server_context_t));
    if (!ctx)
    {
        ESP_LOGE(TAG, "Failed to allocate memory for REST context");
        return ESP_ERR_NO_MEM;
    }

    strlcpy(ctx->base_path, base_path, sizeof(ctx->base_path));

    httpd_config_t config = HTTPD_DEFAULT_CONFIG();
    config.uri_match_fn = httpd_uri_match_wildcard;
    config.max_uri_handlers = 32;

    // Aumenta stack do httpd (handlers + cJSON + etc)
    config.stack_size = 8192; // tenta 8192; se necessário 12288
    config.task_priority = tskIDLE_PRIORITY + 5;

    // Opcional (ajuda com muitas conexões/keep-alive)
    config.lru_purge_enable = true;

    httpd_handle_t server = NULL;
    esp_err_t err = httpd_start(&server, &config);
    if (err != ESP_OK)
    {
        ESP_LOGE(TAG, "Failed to start HTTP server: %s", esp_err_to_name(err));
        free(ctx);
        return err;
    }

    ESP_LOGI(TAG, "HTTP server started successfully");

    // Registar handlers
    register_evse_settings_handlers(server, ctx);
    register_network_handlers(server, ctx);
    register_ocpp_handlers(server, ctx);
    register_auth_handlers(server, ctx);
    register_dashboard_handlers(server, ctx);
    register_meters_settings_handlers(server, ctx);
    register_loadbalancing_settings_handlers(server, ctx);
    register_link_config_handlers(server, ctx);
    register_meters_data_handlers(server, ctx);
    register_scheduler_settings_handlers(server, ctx);
    register_system_handlers(server, ctx);
    register_static_file_handlers(server, ctx);

    ESP_LOGI(TAG, "All REST API endpoint groups registered successfully");
    return ESP_OK;
}
