// POST /api/devices/layout — Update the XML layout for a device
// Body: {"mac": "AA:BB:CC:DD:EE:FF", "xml": "<lv_label .../>"}

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

#include "types.hpp"
#include "device.hpp"

internal const char *kTagDeviceLayout = "API_DEV_LAYOUT";

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

  // The XML payload can be large, so use a bigger buffer
  // DEVICE_XML_MAX (2048) + JSON overhead for mac key etc.
  constexpr int kBufSize = DEVICE_XML_MAX + 256;
  char *buf = (char *)malloc(kBufSize);
  if (!buf)
  {
    httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Out of memory");
    return ESP_FAIL;
  }

  int total = 0;
  int remaining = req->content_len;
  if (remaining >= kBufSize)
  {
    free(buf);
    httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Payload too large");
    return ESP_FAIL;
  }

  while (remaining > 0)
  {
    int received = httpd_req_recv(req, buf + total, remaining);
    if (received <= 0)
    {
      free(buf);
      httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Receive error");
      return ESP_FAIL;
    }
    total += received;
    remaining -= received;
  }
  buf[total] = '\0';

  cJSON *body = cJSON_Parse(buf);
  free(buf);

  if (!body)
  {
    httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid JSON");
    return ESP_FAIL;
  }

  cJSON *mac_item = cJSON_GetObjectItem(body, "mac");
  cJSON *xml_item = cJSON_GetObjectItem(body, "xml");

  if (!cJSON_IsString(mac_item) || !mac_item->valuestring || strlen(mac_item->valuestring) == 0)
  {
    cJSON_Delete(body);
    httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing 'mac'");
    return ESP_FAIL;
  }

  if (!cJSON_IsString(xml_item) || !xml_item->valuestring)
  {
    cJSON_Delete(body);
    httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing 'xml'");
    return ESP_FAIL;
  }

  bool ok = update_device_layout(mac_item->valuestring, xml_item->valuestring);

  if (!ok)
  {
    cJSON_Delete(body);
    httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "Device not found");
    return ESP_FAIL;
  }

  ESP_LOGI(kTagDeviceLayout, "Updated layout for %s (%zu bytes)", mac_item->valuestring,
           strlen(xml_item->valuestring));

  cJSON_Delete(body);

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

internal const httpd_uri_t api_devices_layout_uri = {
    .uri = "/api/devices/layout",
    .method = HTTP_POST,
    .handler = api_devices_layout_handler,
    .user_ctx = NULL};
