/**
 * @file hal_http.c
 * @brief HAL HTTP 客户端实现（JieLi 平台）
 */

#include "hal_http.h"
#include "hal_log.h"
#include "system/includes.h"
#include "http/http_cli.h"
#include <stdlib.h>
#include <string.h>

#define TAG  "HAL_HTTP"

#define HTTP_RECV_BUF_SIZE  4096
#define HTTP_TIMEOUT_SEC    10

typedef struct {
    int placeholder; /* JieLi http_cli is stateless per request */
} hal_http_impl_t;

hal_http_handle_t hal_http_create(void)
{
    hal_http_impl_t *impl = (hal_http_impl_t *)zalloc(sizeof(hal_http_impl_t));
    return (hal_http_handle_t)impl;
}

int hal_http_post(hal_http_handle_t handle,
                  const char *url,
                  const char *content_type,
                  const void *body,
                  size_t body_len,
                  hal_http_response_t *response)
{
    if (!handle || !url || !response) {
        return -1;
    }

    memset(response, 0, sizeof(*response));

    http_body_obj http_body = {0};
    http_body.recv_len = 0;
    http_body.buf_len = HTTP_RECV_BUF_SIZE;
    http_body.buf_count = 1;
    http_body.p = (char *)malloc(HTTP_RECV_BUF_SIZE);
    if (!http_body.p) {
        return -1;
    }

    httpcli_ctx ctx = {0};
    ctx.url = (char *)url;
    ctx.timeout_millsec = HTTP_TIMEOUT_SEC * 1000;
    ctx.data_format = (char *)content_type;
    ctx.post_data = (char *)body;
    ctx.data_len = body_len;
    ctx.priv = &http_body;

    int ret = httpcli_post(&ctx);
    if (ret == HERROR_OK) {
        response->status_code = 200;
        response->body = http_body.p;
        response->body_len = http_body.recv_len;
        return 0;
    }

    free(http_body.p);
    BD_LOGE(TAG, "HTTP POST fail: %d", ret);
    return -1;
}

int hal_http_get(hal_http_handle_t handle,
                 const char *url,
                 hal_http_response_t *response)
{
    if (!handle || !url || !response) {
        return -1;
    }

    memset(response, 0, sizeof(*response));

    http_body_obj http_body = {0};
    http_body.recv_len = 0;
    http_body.buf_len = HTTP_RECV_BUF_SIZE;
    http_body.buf_count = 1;
    http_body.p = (char *)malloc(HTTP_RECV_BUF_SIZE);
    if (!http_body.p) {
        return -1;
    }

    httpcli_ctx ctx = {0};
    ctx.url = (char *)url;
    ctx.timeout_millsec = HTTP_TIMEOUT_SEC * 1000;
    ctx.priv = &http_body;

    int ret = httpcli_get(&ctx);
    if (ret == HERROR_OK) {
        response->status_code = 200;
        response->body = http_body.p;
        response->body_len = http_body.recv_len;
        return 0;
    }

    free(http_body.p);
    BD_LOGE(TAG, "HTTP GET fail: %d", ret);
    return -1;
}

void hal_http_response_free(hal_http_response_t *response)
{
    if (!response) {
        return;
    }
    if (response->body) {
        free(response->body);
        response->body = NULL;
    }
    response->body_len = 0;
}

void hal_http_destroy(hal_http_handle_t handle)
{
    if (handle) {
        free(handle);
    }
}
