// GET /api/tasks?user_id=N — List tasks for a specific user

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

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

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

  char query[64] = {};
  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 'user_id'");
    return ESP_FAIL;
  }

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

  uint8 user_id = (uint8)atoi(user_id_str);

  cJSON *arr = cJSON_CreateArray();

  for (int i = 0; i < MAX_TASKS; i++)
  {
    if (g_Tasks[i].active && g_Tasks[i].user_id == user_id)
    {
      cJSON *obj = cJSON_CreateObject();
      cJSON_AddNumberToObject(obj, "id", g_Tasks[i].id);
      cJSON_AddNumberToObject(obj, "user_id", g_Tasks[i].user_id);
      cJSON_AddStringToObject(obj, "title", g_Tasks[i].title);
      cJSON_AddNumberToObject(obj, "due_date", (double)g_Tasks[i].due_date);
      cJSON_AddNumberToObject(obj, "period", g_Tasks[i].period);
      cJSON_AddNumberToObject(obj, "recurrence", g_Tasks[i].recurrence);
      cJSON_AddBoolToObject(obj, "completed", g_Tasks[i].completed);
      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_tasks_get_uri = {.uri = "/api/tasks",
                                                .method = HTTP_GET,
                                                .handler =
                                                    api_tasks_get_handler,
                                                .user_ctx = NULL};
