// DELETE /api/users?id=N — Delete a user and cascade-delete their tasks

#include "esp_http_server.h"

#include "api/tasks/store.hpp"
#include "api/users/store.hpp"
#include "types.hpp"

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

  char query[32] = {};
  if (httpd_req_get_url_query_str(req, query, sizeof(query)) != ESP_OK)
  {
    httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing query param 'id'");
    return ESP_FAIL;
  }

  char id_str[8] = {};
  if (httpd_query_key_value(query, "id", id_str, sizeof(id_str)) != ESP_OK)
  {
    httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing query param 'id'");
    return ESP_FAIL;
  }

  uint8 id = (uint8)atoi(id_str);

  // Cascade: remove all tasks belonging to this user
  remove_tasks_for_user(id);

  if (!remove_user(id))
  {
    httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "User not found");
    return ESP_FAIL;
  }

  httpd_resp_sendstr(req, "{\"status\":\"ok\"}");
  return ESP_OK;
}

internal const httpd_uri_t api_users_delete_uri = {.uri = "/api/users",
                                                   .method = HTTP_DELETE,
                                                   .handler =
                                                       api_users_delete_handler,
                                                   .user_ctx = NULL};
