// POST /api/users — Create a new user
// Body: {"name": "Alice"}

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

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


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

  char buf[128];
  int received = httpd_req_recv(req, buf, sizeof(buf) - 1);
  if (received <= 0)
  {
    httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Empty body");
    return ESP_FAIL;
  }
  buf[received] = '\0';

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

  cJSON *name_item = cJSON_GetObjectItem(body, "name");
  if (!cJSON_IsString(name_item) || strlen(name_item->valuestring) == 0)
  {
    cJSON_Delete(body);
    httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing 'name'");
    return ESP_FAIL;
  }

  user_t *user = add_user(name_item->valuestring);
  cJSON_Delete(body);

  if (!user)
  {
    httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR,
                        "User limit reached");
    return ESP_FAIL;
  }

  cJSON *resp = cJSON_CreateObject();
  cJSON_AddNumberToObject(resp, "id", user->id);
  cJSON_AddStringToObject(resp, "name", user->name);

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

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

  return ESP_OK;
}

internal const httpd_uri_t api_users_post_uri = {.uri = "/api/users",
                                                 .method = HTTP_POST,
                                                 .handler =
                                                     api_users_post_handler,
                                                 .user_ctx = NULL};
