// POST /api/tasks — Create a new task
// Body: {"user_id":1, "title":"...", "due_date":1741369200, "period":0,
// "recurrence":0}

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

#include "todo.hpp"
#include "types.hpp"

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

  char buf[256];
  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 *user_id_item = cJSON_GetObjectItem(body, "user_id");
  cJSON *title_item = cJSON_GetObjectItem(body, "title");
  cJSON *due_date_item = cJSON_GetObjectItem(body, "due_date");
  cJSON *period_item = cJSON_GetObjectItem(body, "period");
  cJSON *recurrence_item = cJSON_GetObjectItem(body, "recurrence");

  if (!cJSON_IsNumber(user_id_item) || !cJSON_IsString(title_item))
  {
    cJSON_Delete(body);
    httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing user_id or title");
    return ESP_FAIL;
  }

  int64 due_date =
      cJSON_IsNumber(due_date_item) ? (int64)due_date_item->valuedouble : 0;
  uint8 period = cJSON_IsNumber(period_item) ? (uint8)period_item->valueint
                                             : (uint8)PERIOD_MORNING;
  uint8 recurrence =
      cJSON_IsNumber(recurrence_item) ? (uint8)recurrence_item->valueint : 0;

  task_t *task =
      add_task((uint8)user_id_item->valueint, title_item->valuestring, due_date,
               period, recurrence);
  cJSON_Delete(body);

  if (!task)
  {
    httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR,
                        "Task limit reached or invalid user");
    return ESP_FAIL;
  }

  cJSON *resp = cJSON_CreateObject();
  cJSON_AddNumberToObject(resp, "id", task->id);
  cJSON_AddNumberToObject(resp, "user_id", task->user_id);
  cJSON_AddStringToObject(resp, "title", task->title);
  cJSON_AddNumberToObject(resp, "due_date", (double)task->due_date);
  cJSON_AddNumberToObject(resp, "period", task->period);
  cJSON_AddNumberToObject(resp, "recurrence", task->recurrence);
  cJSON_AddBoolToObject(resp, "completed", task->completed);

  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_tasks_post_uri = {.uri = "/api/tasks",
                                                 .method = HTTP_POST,
                                                 .handler =
                                                     api_tasks_post_handler,
                                                 .user_ctx = NULL};
