// DELETE /api/tasks?id=N — Delete a task

#include "esp_http_server.h"

#include "types.hpp"

internal esp_err_t api_tasks_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;
  }

  uint16 id = (uint16)atoi(id_str);

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

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

internal const httpd_uri_t api_tasks_delete_uri = {.uri = "/api/tasks",
                                                   .method = HTTP_DELETE,
                                                   .handler =
                                                       api_tasks_delete_handler,
                                                   .user_ctx = NULL};
