// GET /api/users — List all active users

#include "cJSON.h"
#include "esp_http_server.h"

#include "types.hpp"
#include "user.hpp"


internal esp_err_t api_users_get_handler(httpd_req_t *req)
{
  httpd_resp_set_type(req, "application/json");
  httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");

  cJSON *arr = cJSON_CreateArray();

  for (int i = 0; i < MAX_USERS; i++)
  {
    if (g_Users[i].active)
    {
      cJSON *obj = cJSON_CreateObject();
      cJSON_AddNumberToObject(obj, "id", g_Users[i].id);
      cJSON_AddStringToObject(obj, "name", g_Users[i].name);
      cJSON_AddItemToArray(arr, obj);
    }
  }

  const char *json = cJSON_PrintUnformatted(arr);
  httpd_resp_sendstr(req, json);

  free((void *)json);
  cJSON_Delete(arr);

  return ESP_OK;
}

internal const httpd_uri_t api_users_get_uri = {.uri = "/api/users",
                                                .method = HTTP_GET,
                                                .handler =
                                                    api_users_get_handler,
                                                .user_ctx = NULL};
