/*
 * Copyright (C) 2026 Sophie Sitzler
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

// @file http.h

#ifndef _SO_HTTP_H
#define _SO_HTTP_H

#include <stdbool.h>
#include <sys/socket.h>

// @include <openssl/ssl.h>
// @desc OpenSSL library handling TLS/SSL.
#include <openssl/ssl.h>

#ifdef SO_HTTP_IMPL
#define SO_SOCK_IMPL
#endif // SO_HTTP_IMPL

// @include <so/sock.h>
// @desc so/sock library handling server/client communication and multi-threading.
#include <so/sock.h>

// @enum http_err_t
// @desc Error code.
typedef enum {
  HTTP_ERR_OK = SOCK_ERR_OK,
  HTTP_ERR__COUNT,
} http_err_t;

// @enum http_status_t
// @desc HTTP status code.
typedef enum {
  HTTP_STATUS_CONTINUE                        = 100,
  HTTP_STATUS_SWITCHING_PROTOCOLS             = 101,
  HTTP_STATUS_PROCESSING                      = 102,
  HTTP_STATUS_EARLY_HINTS                     = 103,
  HTTP_STATUS_OK                              = 200,
  HTTP_STATUS_CREATED                         = 201,
  HTTP_STATUS_ACCEPTED                        = 202,
  HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION   = 203,
  HTTP_STATUS_NO_CONTENT                      = 204,
  HTTP_STATUS_RESET_CONTENT                   = 205,
  HTTP_STATUS_PARTIAL_CONTENT                 = 206,
  HTTP_STATUS_MULTI_STATUS                    = 207,
  HTTP_STATUS_ALREADY_REPORTED                = 208,
  HTTP_STATUS_IM_USED                         = 226,
  HTTP_STATUS_MULTIPLE_CHOICES                = 300,
  HTTP_STATUS_MOVED_PERMANENTLY               = 301,
  HTTP_STATUS_FOUND                           = 302,
  HTTP_STATUS_SEE_OTHER                       = 303,
  HTTP_STATUS_NOT_MODIFIED                    = 304,
  HTTP_STATUS_TEMPORARY_REDIRECT              = 307,
  HTTP_STATUS_PERMANENT_REDIRECT              = 308,
  HTTP_STATUS_BAD_REQUEST                     = 400,
  HTTP_STATUS_UNAUTHORIZED                    = 401,
  HTTP_STATUS_PAYMENT_REQUIRED                = 402,
  HTTP_STATUS_FORBIDDEN                       = 403,
  HTTP_STATUS_NOT_FOUND                       = 404,
  HTTP_STATUS_METHOD_NOT_ALLOWED              = 405,
  HTTP_STATUS_NOT_ACCEPTABLE                  = 406,
  HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED   = 407,
  HTTP_STATUS_REQUEST_TIMEOUT                 = 408,
  HTTP_STATUS_CONFLICT                        = 409,
  HTTP_STATUS_GONE                            = 410,
  HTTP_STATUS_LENGTH_REQUIRED                 = 411,
  HTTP_STATUS_PRECONDITION_FAILED             = 412,
  HTTP_STATUS_PAYLOAD_TOO_LARGE               = 413,
  HTTP_STATUS_URI_TOO_LONG                    = 414,
  HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE          = 415,
  HTTP_STATUS_RANGE_NOT_SATISFIABLE           = 416,
  HTTP_STATUS_EXPECTATION_FAILED              = 417,
  HTTP_STATUS_I_AM_A_TEAPOT                   = 418,
  HTTP_STATUS_MISDIRECTED_REQUEST             = 421,
  HTTP_STATUS_UNPROCESSABLE_CONTENT           = 422,
  HTTP_STATUS_LOCKED                          = 423,
  HTTP_STATUS_FAILED_DEPENDENCY               = 424,
  HTTP_STATUS_TOO_EARLY                       = 425,
  HTTP_STATUS_UPGRADE_REQUIRED                = 426,
  HTTP_STATUS_PRECONDITION_REQUIRED           = 428,
  HTTP_STATUS_TOO_MANY_REQUESTS               = 429,
  HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
  HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS   = 451,
  HTTP_STATUS_INTERNAL_SERVER_ERROR           = 500,
  HTTP_STATUS_NOT_IMPLEMENTED                 = 501,
  HTTP_STATUS_BAD_GATEWAY                     = 502,
  HTTP_STATUS_SERVICE_UNAVAILABLE             = 503,
  HTTP_STATUS_GATEWAY_TIMEOUT                 = 504,
  HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED      = 505,
  HTTP_STATUS_VARIANT_ALSO_NEGOTITATES        = 506,
  HTTP_STATUS_INSUFFICIENT_STORAGE            = 507,
  HTTP_STATUS_LOOP_DETECTED                   = 508,
  HTTP_STATUS_NOT_EXTENDED                    = 510,
  HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511,
  __HTTP_STATUS_HANDLED                       = 999,
} http_status_t;

// @type http_t
// @groupdef http_t
// @desc Global context struct. Implemented here {http}.
typedef struct http http_t;

// @type http_host_t
// @desc Represents a the host.
typedef sock_host_t http_host_t;

// @type http_bind_t
// @desc Represents a the binding (port).
typedef sock_bind_t http_bind_t;

// @type http_conn_t
// @groupdef http_conn_t
// @desc Represents a client connection.
typedef sock_conn_t http_conn_t;

// @struct http_header_t
// @desc A HTTP header.
typedef struct {
  char *key;
  char *value;
} http_header_t;

// @struct http_req_t
// @groupdef http_req_t
// @desc A HTTP request struct.
typedef struct {
  http_conn_t *conn;
  char *method;
  char *url;
  char *version;
  http_header_t *headers;
  int headers_len;
  char *body;
  long body_len;
  void *ext_data;
} http_req_t;

// @struct http_resp_t
// @groupdef http_resp_t
// @desc A HTTP response struct.
typedef struct {
  char *version;
  http_status_t status;
  http_header_t *headers;
  int headers_len;
  char *body;
  long body_len;
} http_resp_t;

// @type http_global_fn_t
// @desc A function type for a global route handler.
typedef http_resp_t (*http_global_fn_t)(http_t *, http_req_t *);

// @type http_handle_fn_t
// @desc A function type for a route handler.
typedef http_resp_t (*http_handle_fn_t)(http_req_t *);

// @type http_hook_fn_t
// @desc A function type for a hook handler.
typedef void (*http_hook_fn_t)(http_req_t *);

// @struct http_route_t
// @desc A route.
typedef struct {
  char *method;
  char *path;
  http_handle_fn_t fn;
} http_route_t;

// @struct http_pair_t
typedef struct {
  char *key;
  char *value;
} http_pair_t;

// @struct http_pairs_t
// @groupdef http_pairs_t
typedef struct {
  http_pair_t *pairs;
  size_t len;
} http_pairs_t;

// @struct http
// @group http_t
// @desc Implementation of the global context struct. Type here {http_t}.
struct http {
  sock_t *sock;
  http_global_fn_t fn;
};

// @func http_init
// @group http_t
// @desc Initializes global library context {http_t}. Free with {http_cleanup}.
// @return {http_t} * - Returns the global library context.
http_t *http_init(void);

// @func http_cleanup
// @group http_t
// @desc Cleans up {http_t}.
// @param {http_t} *self - The global library context.
void http_cleanup(http_t *self);

// @func http_on_global
// @group http_t
// @desc Set and override the default global route handler {_http_on_global}.
// @param {http_t} *self - The global library context.
// @param {http_global_fn_t} fn - The global route handler.
void http_on_global(http_t *self, http_global_fn_t fn);

// @func http_on_route
// @note Use macros like {HTTP_GET} and others to register routes more easily.
// @desc Registers a new route.
// @param char *method - The HTTP method.
// @param char *url - The HTTP URL (path).
// @param {http_handle_fn_t} fn - The route handler.
void http_on_route(char *method, char *url, http_handle_fn_t fn);

// @func http_on_default
// @note Use macro {HTTP_DEFAULT} instead.
// @desc Registers a fallback handler.
// @param {http_handle_fn_t} fn - The route handler.
void http_on_default(http_handle_fn_t fn);

// @func http_on_pre_route
// @note Use macro {HTTP_PRE_HOOK} instead.
// @desc Registers a hook handler which is performed before the route handler is executed.
// @param {http_hook_fn_t} fn - The hook handler.
void http_on_pre_route(http_hook_fn_t fn);

// @func http_on_post_route
// @note Use macro {HTTP_POST_HOOK} instead.
// @desc Registers a hook handler which is performed after the route handler is executed.
// @param {http_hook_fn_t} fn - The hook handler.
void http_on_post_route(http_hook_fn_t fn);

// @func http_req_path
// @group http_req_t
// @param {http_req_t} *req - The HTTP request.
// @return char * - Returns the request path.
char *http_req_path(http_req_t *req);

// @func http_req_body
// @group http_req_t
// @param {http_req_t} *req - The HTTP request.
// @return char * - Returns the request body.
char *http_req_body(http_req_t *req);

// @func http_req_queries
// @group http_req_t
// @param {http_req_t} *req - The HTTP request.
// @return {http_pairs_t} - Returns the request queries.
http_pairs_t http_req_queries(http_req_t *req);

// @func http_req_params
// @group http_req_t
// @param {http_req_t} *req - The HTTP request.
// @return {http_pairs_t} - Returns the request params.
http_pairs_t http_req_params(http_req_t *req);

// @func http_pairs_get
// @group http_pairs_t
char *http_pairs_get(http_pairs_t *self, char *key);

// @func http_pairs_has
// @group http_pairs_t
bool http_pairs_has(http_pairs_t *self, char *key);

// @func http_pairs_free
// @group http_pairs_t
void http_pairs_free(http_pairs_t *self);

// @func http_req_header
// @group http_req_t
// @param {http_req_t} *req - The HTTP request.
// @param char *key - The header key.
// @return char * - Returns a header value.
char *http_req_header(http_req_t *req, char *key);

// @func http_resp_header
// @group http_resp_t
// @desc Writes a header to the response. The header content is consumed and can be freed afterward.
// @param {http_resp_t} *resp - The HTTP response.
// @param char *key - The header key.
// @param char *value - The header value.
void http_resp_header(http_resp_t *resp, char *key, char *value);

// @func http_resp_create
// @group http_resp_t
// @desc Creates a new response with a given HTTP status. Freed with {http_resp_free}.
// @param {http_status_t} status - The HTTP status code.
// @return {http_resp_t} - Returns a HTTP response.
http_resp_t http_resp_create(http_status_t status);

// @func http_resp_body
// @group http_resp_t
// @desc Writes body content to the response. The body content is consumed and can be freed afterward.
// @param {http_resp_t} *resp - The HTTP response.
// @param char *body - The body content.
// @param long len - The body  length.
void http_resp_body(http_resp_t *resp, char *body, long len);

// @func http_req_free
// @group http_req_t
// @desc Frees a request.
// @param {http_req_t} *req - The HTTP request.
void http_req_free(http_req_t *req);

// @func http_resp_write_head
// @group http_resp_t
// @desc Writes a response header  to the socket stream.
// @param {http_resp_t} *resp - The HTTP response.
// @param {http_conn_t} *conn - The HTTP connection.
void http_resp_write_head(http_resp_t *resp, http_conn_t *conn);

// @func http_resp_write_body
// @group http_resp_t
// @desc Writes a response body to the socket stream.
// @param {http_resp_t} *resp - The HTTP response.
// @param {http_conn_t} *conn - The HTTP connection.
void http_resp_write_body(http_resp_t *resp, http_conn_t *conn);

// @func http_resp_write
// @group http_resp_t
// @desc Writes a response to the socket stream.
// @param {http_resp_t} *resp - The HTTP response.
// @param {http_conn_t} *conn - The HTTP connection.
void http_resp_write(http_resp_t *resp, http_conn_t *conn);

// @func http_resp_free
// @group http_resp_t
// @desc Frees a response.
// @param {http_resp_t} *resp - The HTTP response.
void http_resp_free(http_resp_t *resp);

// @func http_bind
// @group http_t
// @param {http_t} *self - The global library context.
// @param char *hostname - The hostname.
// @param int port - The port.
// @param {http_host_t} *hosts - The host to bind to.
// @param int hosts_len - The host length of to be bound host.
http_err_t http_bind(http_t *self, char *hostname, int port, http_host_t *hosts, int hosts_len);

// @func http_listen
// @group http_t
// @param {http_t} *self - The global library context.
http_err_t http_listen(http_t *self);

// @func http_bind_listen
// @group http_t
// @param {http_t} *self - The global library context.
// @param char *hostname - The hostname.
// @param int port - The port.
http_err_t http_bind_listen(http_t *self, char *hostname, int port);

// @func http_close
// @group http_t
// @param {http_t} *self - The global library context.
void http_close(http_t *self);

// @func _http_req_read
// @group http_req_t
// @internal
// @param {http_req_t} *req - The HTTP request.
// @param {http_conn_t} *conn - The HTTP connection.
// @return {http_err_t} - Returns an HTTP error code.
http_err_t _http_req_read(http_req_t *req, http_conn_t *conn);

#ifdef SO_HTTP_IMPL

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <netdb.h>
#include <poll.h>
#include <errno.h>
#include <signal.h>

// @macro HTTP_VERSION
// @internal
#define HTTP_VERSION "HTTP/1.1"

// @macro HTTP_MAX_REQUEST_HEAD_SIZE
// @internal
#define HTTP_MAX_REQUEST_HEAD_SIZE 1000000

// @macro HTTP_RESP_HANDLED
// @group http_resp_t
// @desc Handled {http_resp_t}.
#define HTTP_RESP_HANDLED (http_resp_t) { .status = __HTTP_STATUS_HANDLED }

// @macro _HTTP_ON
// @internal
#define _HTTP_ON(method, path, fn_name) \
  static http_resp_t fn_name(http_req_t *req); \
  __attribute__((constructor)) \
  static void __macro_http_fn_register_##fn_name() { \
    http_on_route(method, path, &fn_name); \
  } \
  static http_resp_t fn_name(http_req_t *req)

// @macro HTTP_GET
#define HTTP_GET(path, fn_name) _HTTP_ON("GET", path, fn_name)

// @macro HTTP_GET
#define HTTP_HEAD(path, fn_name) _HTTP_ON("HEAD", path, fn_name)

// @macro HTTP_POST
#define HTTP_POST(path, fn_name) _HTTP_ON("POST", path, fn_name)

// @macro HTTP_PUT
#define HTTP_PUT(path, fn_name) _HTTP_ON("PUT", path, fn_name)

// @macro HTTP_DELETE
#define HTTP_DELETE(path, fn_name) _HTTP_ON("DELETE", path, fn_name)

// @macro HTTP_CONNECT
#define HTTP_CONNECT(path, fn_name) _HTTP_ON("CONNECT", path, fn_name)

// @macro HTTP_OPTIONS
#define HTTP_OPTIONS(path, fn_name) _HTTP_ON("OPTIONS", path, fn_name)

// @macro HTTP_TRACE
#define HTTP_TRACE(path, fn_name) _HTTP_ON("TRACE", path, fn_name)

// @macro HTTP_PATCH
#define HTTP_PATCH(path, fn_name) _HTTP_ON("PATCH", path, fn_name)

// @macro HTTP_DEFAULT
#define HTTP_DEFAULT(fn_name) \
  static http_resp_t fn_name(http_req_t *req); \
  __attribute__((constructor)) \
  static void __macro_http_fn_register_##fn_name() { \
    http_on_default(&fn_name); \
  } \
  static http_resp_t fn_name(http_req_t *req)

// @macro HTTP_PRE_HOOK
#define HTTP_PRE_HOOK(fn_name) \
  static void fn_name(http_req_t *req); \
  __attribute__((constructor)) \
  static void __macro_http_fn_register_##fn_name() { \
    http_on_pre_route(&fn_name); \
  } \
  static void fn_name(http_req_t *req)

// @macro HTTP_POST_HOOK
#define HTTP_POST_HOOK(fn_name) \
  static void fn_name(http_req_t *req); \
  __attribute__((constructor)) \
  static void __macro_http_fn_register_##fn_name() { \
    http_on_post_route(&fn_name); \
  } \
  static void fn_name(http_req_t *req)

// @global _http_routes
// @internal
http_route_t *_http_routes = NULL;

// @global _http_routes_len
// @internal
size_t _http_routes_len = 0;

// @global _http_default_route
// @internal
http_handle_fn_t _http_default_route;

// @global _http_pre_route
// @internal
http_hook_fn_t _http_pre_route;

// @global _http_post_route
// @internal
http_hook_fn_t _http_post_route;

// @func _http_on_global
// @group http_t
// @internal
// @desc The default route handler. Can be overwritten with {http_on_global}.
// @param {http_t} *self - The global library context.
// @param {http_req_t} *req - The HTTP request.
// @return {http_resp_t} - Returns a HTTP response.
http_resp_t _http_on_global(http_t *self, http_req_t *req) {
  http_resp_t resp = http_resp_create(HTTP_STATUS_NOT_FOUND);
  if (_http_pre_route != NULL) {
    _http_pre_route(req);
  }
  for (size_t i = 0; i < _http_routes_len; i++) {
    http_route_t *route = &_http_routes[i];
    char *path = http_req_path(req);
    if (strcmp(route->method, req->method) == 0) {
      size_t len = strlen(route->path);
      char c = route->path[len - 1];
      if (c == '*') {
        if (strncmp(route->path, path, len - 1) == 0) {
          http_resp_free(&resp);
          resp = route->fn(req);
        }
      }
      else {
        if (strcmp(route->path, path) == 0) {
          http_resp_free(&resp);
          resp = route->fn(req);
        }
      }
    }
    free(path);
    if (resp.status != HTTP_STATUS_NOT_FOUND) {
      if (_http_post_route != NULL) {
        _http_post_route(req);
      }
      return resp;
    }
  }
  if (_http_default_route != NULL) {
    http_resp_free(&resp);
    resp = _http_default_route(req);
  }
  if (_http_post_route != NULL) {
    _http_post_route(req);
  }
  return resp;
}

// @func _http_on_handle
// @internal
sock_err_t _http_on_handle(sock_t *sock, http_conn_t *conn) {
  http_t *self= (http_t *) sock->ext;
  http_req_t req;
  http_err_t err = _http_req_read(&req, conn);
  if (err != HTTP_ERR_OK) {
    return err;
  }
  if (req.method != NULL && req.url != NULL) {
    if (self->fn != NULL) {
      http_resp_t resp = self->fn(self, &req);
      http_resp_write(&resp, conn);
      http_resp_free(&resp);
    }
  }
  http_req_free(&req);
  return HTTP_ERR_OK;
}

http_t *http_init(void) {
  http_t *self = (http_t *) malloc(sizeof(http_t));
  *self = (http_t) {
    .sock = sock_init(),
    .fn = &_http_on_global,
  };
  sock_set_ext(self->sock, self);
  sock_on_global(self->sock, _http_on_handle);
  return self;
}

void http_cleanup(http_t *self) {
  if (self->sock != NULL) {
    sock_cleanup(self->sock);
  }
  free(self);
}

void http_on_global(http_t *self, http_global_fn_t fn) {
  self->fn = fn;
}

void http_on_route(char *method, char *path, http_handle_fn_t fn) {
  _http_routes = realloc(_http_routes, sizeof(http_route_t) * (_http_routes_len + 1));
  _http_routes[_http_routes_len] = (http_route_t) {
    .method = method,
    .path = path,
    .fn = fn,
  };
  _http_routes_len++;
}

void http_on_default(http_handle_fn_t fn) {
  _http_default_route = fn;
}

void http_on_pre_route(http_hook_fn_t fn) {
  _http_pre_route = fn;
}

void http_on_post_route(http_hook_fn_t fn) {
  _http_post_route = fn;
}

char *http_req_path(http_req_t *req) {
  char *uri = req->url;
  size_t url_len = strlen(uri);
  size_t i = 0;
  for (; i < url_len; i++) {
    size_t c = uri[i];
    if (c == '?') {
      break;
    }
  }
  size_t len = i;
  char *path = malloc(len + 1);
  memcpy(path, uri, len);
  path[len] = '\0';
  return path;
}

char *http_req_body(http_req_t *req) {
  return req->body;
}

// @func _http_pair_decode
// @internal
char *_http_pair_decode(char *str, size_t len) {
  size_t j = 0;
  size_t k = 0;
  char decoded[len + 1];
  while (j < len) {
    if (str[j] == '%') {
      if (j + 2 < len && isxdigit(str[j + 1]) && isxdigit(str[j + 2])) {
        char hex[3] = { str[j + 1], str[j + 2], '\0' };
        decoded[k++] = (char) strtol(hex, NULL, 16);
        j += 3;
        continue;
      }
      decoded[k++] = '%';
      j++;
      continue;
    }
    if (str[j] == '+') {
      decoded[k++] = ' ';
      j++;
      continue;
    }
    decoded[k++] = str[j++];
  }
  decoded[k] = '\0';
  size_t ret_len = strlen(decoded);
  char *ret = malloc(ret_len + 1);
  memcpy(ret, decoded, ret_len);
  ret[ret_len] = '\0';
  return ret;
}

// @func _http_pairs_init
// @group http_pairs_t
// @internal
http_pairs_t _http_pairs_init(char *uri) {
  http_pairs_t self = (http_pairs_t) {
    .pairs = NULL,
    .len = 0,
  };
  int url_len = strlen(uri);
  size_t set = 0;
  size_t lim = 0;
  for (size_t i = 0; i < url_len + 1; i++) {
    char c = uri[i];
    // find 'key=value' pair
    if (i == url_len || uri[i] == '&') {
      size_t key_len = i - set;
      if (key_len > 0) {
        if (lim > set) {
          key_len = lim - set;
        }
        self.pairs = realloc(self.pairs, sizeof(http_pair_t) * (self.len + 1));
        http_pair_t *pair = &self.pairs[self.len];
        // read key
        pair->key = _http_pair_decode(uri + set, key_len);
        pair->value = NULL;
        if (i > set + key_len + 1) {
          // read value
          size_t value_len = i - (set + key_len + 1);
          pair->value = _http_pair_decode(uri + set + key_len + 1, value_len);
        }
        self.len++;
      }
      set = i + 1;
    }
    // find '=' delimiter
    if (uri[i] == '=') {
      lim = i;
    }
  }
  return self;
}

http_pairs_t http_req_queries(http_req_t *req) {
  size_t url_len = strlen(req->url);
  // skip path
  for (size_t i = 0; i < url_len; i++) {
    if (req->url[i] == '?') {
      return _http_pairs_init(req->url + i + 1);
    }
  }
  return (http_pairs_t) {
    .pairs = NULL,
    .len = 0,
  };
}

http_pairs_t http_req_params(http_req_t *req) {
  return _http_pairs_init(req->body);
}

char *http_pairs_get(http_pairs_t *self, char *key) {
  if (self && self->len > 0) {
    for (size_t i = 0; i < self->len; i++) {
      http_pair_t *pair = &self->pairs[i];
      if (strcmp(pair->key, key) == 0) {
        return pair->value;
      }
    }
  }
  return NULL;
}

bool http_pairs_has(http_pairs_t *self, char *key) {
  if (self && self->len > 0) {
    for (size_t i = 0; i < self->len; i++) {
      http_pair_t *pair = &self->pairs[i];
      if (strcmp(pair->key, key) == 0) {
        return true;
      }
    }
  }
  return false;
}

void http_pairs_free(http_pairs_t *self) {
  if (self == NULL) {
    return;
  }
  if (self->len > 0) {
    for (size_t i = 0; i < self->len; i++) {
      http_pair_t *pair = &self->pairs[i];
      free(pair->key);
      if (pair->value) {
        free(pair->value);
      }
    }
    free(self->pairs);
  }
}

// @func _http_status_str
// @internal
const char *_http_status_str(http_status_t status) {
  switch (status) {
    case HTTP_STATUS_CONTINUE:
      return "Continue";
    case HTTP_STATUS_SWITCHING_PROTOCOLS:
      return "Switching Protocols";
    case HTTP_STATUS_PROCESSING:
      return "Processing";
    case HTTP_STATUS_EARLY_HINTS:
      return "Early Hints";
    case HTTP_STATUS_OK:
      return "OK";
    case HTTP_STATUS_CREATED:
      return "Created";
    case HTTP_STATUS_ACCEPTED:
      return "Accepted";
    case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:
      return "Non-Authoritative Information";
    case HTTP_STATUS_NO_CONTENT:
      return "No Content";
    case HTTP_STATUS_RESET_CONTENT:
      return "Reset Content";
    case HTTP_STATUS_PARTIAL_CONTENT:
      return "Partial Content";
    case HTTP_STATUS_MULTI_STATUS:
      return "Multi-Status";
    case HTTP_STATUS_ALREADY_REPORTED:
      return "Already Reported";
    case HTTP_STATUS_IM_USED:
      return "IM Used";
    case HTTP_STATUS_MULTIPLE_CHOICES:
      return "Multiple Choices";
    case HTTP_STATUS_MOVED_PERMANENTLY:
      return "Moved Permanently";
    case HTTP_STATUS_FOUND:
      return "Found";
    case HTTP_STATUS_SEE_OTHER:
      return "See Other";
    case HTTP_STATUS_NOT_MODIFIED:
      return "Not Modified";
    case HTTP_STATUS_TEMPORARY_REDIRECT:
      return "Temporary Redirect";
    case HTTP_STATUS_PERMANENT_REDIRECT:
      return "Permanent Redirect";
    case HTTP_STATUS_BAD_REQUEST:
      return "Bad Request";
    case HTTP_STATUS_UNAUTHORIZED:
      return "Unauthorized";
    case HTTP_STATUS_PAYMENT_REQUIRED:
      return "Payment Required";
    case HTTP_STATUS_FORBIDDEN:
      return "Forbidden";
    case HTTP_STATUS_NOT_FOUND:
      return "Not Found";
    case HTTP_STATUS_METHOD_NOT_ALLOWED:
      return "Method Not Allowed";
    case HTTP_STATUS_NOT_ACCEPTABLE:
      return "Not Acceptable";
    case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:
      return "Proxy Authentication Required";
    case HTTP_STATUS_REQUEST_TIMEOUT:
      return "Request Timeout";
    case HTTP_STATUS_CONFLICT:
      return "Conflict";
    case HTTP_STATUS_GONE:
      return "Gone";
    case HTTP_STATUS_LENGTH_REQUIRED:
      return "Length Required";
    case HTTP_STATUS_PRECONDITION_FAILED:
      return "Precondition Failed";
    case HTTP_STATUS_PAYLOAD_TOO_LARGE:
      return "Payload Too Large";
    case HTTP_STATUS_URI_TOO_LONG:
      return "URI Too Long";
    case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:
      return "Unsupported Media Type";
    case HTTP_STATUS_RANGE_NOT_SATISFIABLE:
      return "Range Not Satisfiable";
    case HTTP_STATUS_EXPECTATION_FAILED:
      return "Expectation Failed";
    case HTTP_STATUS_I_AM_A_TEAPOT:
      return "I'm a teapot";
    case HTTP_STATUS_MISDIRECTED_REQUEST:
      return "Misdirected Request";
    case HTTP_STATUS_UNPROCESSABLE_CONTENT:
      return "Unprocessable Content";
    case HTTP_STATUS_LOCKED:
      return "Locked";
    case HTTP_STATUS_FAILED_DEPENDENCY:
      return "Failed Dependency";
    case HTTP_STATUS_TOO_EARLY:
      return "Too Early";
    case HTTP_STATUS_UPGRADE_REQUIRED:
      return "Upgrade Required";
    case HTTP_STATUS_PRECONDITION_REQUIRED:
      return "Precondition Required";
    case HTTP_STATUS_TOO_MANY_REQUESTS:
      return "Too Many Requests";
    case HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:
      return "Request Header Fields Too Large";
    case HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:
      return "Unavailable For Legal Reasons";
    case HTTP_STATUS_INTERNAL_SERVER_ERROR:
      return "Internal Server Error";
    case HTTP_STATUS_NOT_IMPLEMENTED:
      return "Not Implemented";
    case HTTP_STATUS_BAD_GATEWAY:
      return "Bad Gateway";
    case HTTP_STATUS_SERVICE_UNAVAILABLE:
      return "Service Unavailable";
    case HTTP_STATUS_GATEWAY_TIMEOUT:
      return "Gateway Timeout";
    case HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:
      return "HTTP Version Not Supported";
    case HTTP_STATUS_VARIANT_ALSO_NEGOTITATES:
      return "Variant Also Negotitates";
    case HTTP_STATUS_INSUFFICIENT_STORAGE:
      return "Insufficient Storage";
    case HTTP_STATUS_LOOP_DETECTED:
      return "Loop Detected";
    case HTTP_STATUS_NOT_EXTENDED:
      return "Not Extended";
    case HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:
      return "Network Authentication Required";
    default:
      return NULL;
  }
}

// @func _http_conn_read
// @group http_conn_t
// @internal
ssize_t _http_conn_read(http_conn_t *conn, char *buffer, size_t len) {
  return sock_conn_read(conn, buffer, len);
}

// @func _http_conn_write
// @group http_conn_t
// @internal
ssize_t _http_conn_write(http_conn_t *conn, char *buffer, size_t len) {
  return sock_conn_write(conn, buffer, len);
}

char *http_req_header(http_req_t *req, char *key) {
  if (req->headers_len > 0) {
    for (int i = 0; i < req->headers_len; i++) {
      http_header_t *header = &req->headers[i];
      if (strcasecmp(header->key, key) == 0) {
        return header->value;
      }
    }
  }
  return NULL;
}

void http_resp_header(http_resp_t *resp, char *key, char *value) {
  resp->headers = (http_header_t *) realloc(resp->headers, sizeof(http_header_t) * (resp->headers_len + 1));
  http_header_t *new_header = &resp->headers[resp->headers_len];
  resp->headers_len++;
  int key_len = strlen(key);
  new_header->key = (char *) malloc(sizeof(char) * (key_len + 1));
  memcpy(new_header->key, key, key_len);
  new_header->key[key_len] = '\0';
  int value_len = strlen(value);
  new_header->value = (char *) malloc(sizeof(char) * (value_len + 1));
  memcpy(new_header->value, value, value_len);
  new_header->value[value_len] = '\0';
}

http_resp_t http_resp_create(http_status_t status) {
  return (http_resp_t) {
    .version = strdup(HTTP_VERSION),
    .status = status,
    .headers = NULL,
    .headers_len = 0,
    .body = NULL,
    .body_len = 0,
  };
}

void http_resp_body(http_resp_t *resp, char *body, long len) {
  if (resp != NULL && body != NULL) {
    resp->body = (char *) malloc(sizeof(char) * len);
    memcpy(resp->body, body, len);
    resp->body_len = len;
  }
}

void http_req_free(http_req_t *req) {
  if (req->method != NULL) {
    free(req->method);
  }
  if (req->url != NULL) {
    free(req->url);
  }
  if (req->version != NULL) {
    free(req->version);
  }
  if (req->headers_len > 0) {
    for (int i = 0; i < req->headers_len; i++) {
      http_header_t *header = &req->headers[i];
      if (header->key != NULL) {
        free(header->key);
      }
      if (header->value != NULL) {
        free(header->value);
      }
    }
    free(req->headers);
  }
  if (req->body != NULL) {
    free(req->body);
  }
  if (req->ext_data != NULL) {
    free(req->ext_data);
  }
}

void http_resp_free(http_resp_t *resp) {
  if (resp->version != NULL) {
    free(resp->version);
  }
  if (resp->headers_len > 0) {
    for (int i = 0; i < resp->headers_len; i++) {
      http_header_t *header = &resp->headers[i];
      if (header->key != NULL) {
        free(header->key);
      }
      if (header->value != NULL) {
        free(header->value);
      }
    }
    if (resp->headers != NULL) {
      free(resp->headers);
    }
  }
  if (resp->body != NULL) {
    free(resp->body);
  }
}

http_err_t _http_req_read(http_req_t *req, http_conn_t *conn) {
  int len = 0;
  int ln = 0;
  int start = 0;
  char buffer[HTTP_MAX_REQUEST_HEAD_SIZE];
  *req = (http_req_t) {
    .conn = conn,
    .method = NULL,
    .url = NULL,
    .version = NULL,
    .headers = NULL,
    .headers_len = 0,
    .body = NULL,
    .body_len = 0,
    .ext_data = NULL,
  };
  while (true) {
    char c;
    int read = _http_conn_read(conn, &c, 1);
    if (read == 0) {
      break;
    }
    // read timeout
    if (read == -1 || read == SSL_ERROR_SYSCALL) {
      if (errno == EWOULDBLOCK || errno == EAGAIN) {
        return SOCK_ERR_READ_TIMEOUT;
      }
    }
    // break if too long
    if (len == HTTP_MAX_REQUEST_HEAD_SIZE) {
      return SOCK_ERR_REQUEST_TOO_LONG;
    }
    buffer[len] = c;
    len++;
    // read head
    if (len >= 2) {
      char *slice = buffer + (len - 2);
      if (strncmp(slice, "\r\n", 2) == 0) {
        int line_len = (len - 2) - start;
        if (line_len > 0) {
          // read line
          char line[line_len + 1];
          memcpy(line, buffer + start, line_len);
          line[line_len] = '\0';
          // read method, url, and version
          if (ln == 0) {
            int arg = 0;
            int start = 0;
            for (int i = 0; i <= line_len; i++) {
              if (line[i] == ' ' || i == line_len) {
                // read method
                if (arg == 0) {
                  int method_length = i - start;
                  req->method = (char *) malloc(sizeof(char) * (method_length + 1));
                  memcpy(req->method, line + start, method_length);
                  req->method[method_length] = '\0';
                }
                // read url
                if (arg == 1) {
                  int url_length = i - start;
                  req->url = (char *) malloc(sizeof(char) * (url_length + 1));
                  memcpy(req->url, line + start, url_length);
                  req->url[url_length] = '\0';
                }
                // read version
                if (arg == 2) {
                  int version_length = i - start;
                  req->version = (char *) malloc(sizeof(char) * (version_length + 1));
                  memcpy(req->version, line + start, version_length);
                  req->version[version_length] = '\0';
                }
                start = i + 1;
                arg++;
              }
            }
          }
          // read headers
          else {
            int sep = 0;
            req->headers = (http_header_t *) realloc(req->headers, sizeof(http_header_t) * (req->headers_len + 1));
            http_header_t *header = &req->headers[req->headers_len];
            req->headers_len++;
            for (int i = 0; i < line_len; i++) {
              if (line[i] == ':') {
                int key_len = i;
                header->key = (char *) malloc(sizeof(char) * (key_len + 1));
                memcpy(header->key, line, key_len);
                header->key[key_len] = '\0';
                sep = i + 2;
                break;
              }
            }
            int value_len = line_len - sep;
            header->value = (char *) malloc(sizeof(char) * (value_len + 1));
            memcpy(header->value, line + sep, value_len);
            header->value[value_len] = '\0';
          }
        }
        start = len;
        ln++;
      }
    }
    // read body
    if (len >= 4) {
      char *slice = buffer + (len - 4);
      if (strncmp(slice, "\r\n\r\n", 4) == 0) {
        char *content_length = http_req_header(req, (char *) "Content-Length");
        if (content_length != NULL) {
          req->body_len = strtol(content_length, NULL, 10);
          if (req->body_len > 0) {
            req->body = (char *) malloc(sizeof(char) * (req->body_len + 1));
            _http_conn_read(conn, req->body, req->body_len);
            req->body[req->body_len] = '\0';
          }
        }
        break;
      }
    }
  }
  return HTTP_ERR_OK;
}

void http_resp_write_head(http_resp_t *resp, http_conn_t *conn) {
  _http_conn_write(conn, resp->version, strlen(resp->version));
  _http_conn_write(conn, (char *) " ", 1);
  char status[4];
  snprintf(status, 4, "%d", resp->status);
  _http_conn_write(conn, status, strlen(status));
  _http_conn_write(conn, (char *) " ", 1);
  const char *status_message = _http_status_str(resp->status);
  _http_conn_write(conn, (char *) status_message, strlen(status_message));
  _http_conn_write(conn, (char *) "\r\n", 2);
  if (resp->headers_len > 0) {
    for (int i = 0; i < resp->headers_len; i++) {
      http_header_t *header = &resp->headers[i];
      _http_conn_write(conn, header->key, strlen(header->key));
      _http_conn_write(conn, (char *) ": ", 2);
      _http_conn_write(conn, header->value, strlen(header->value));
      _http_conn_write(conn, (char *) "\r\n", 2);
    }
  }
  _http_conn_write(conn, (char *) "\r\n", 2);
}

void http_resp_write_body(http_resp_t *resp, http_conn_t *conn) {
  if (resp->body != NULL) {
    _http_conn_write(conn, resp->body, resp->body_len);
  }
}

void http_resp_write(http_resp_t *resp, http_conn_t *conn) {
  if (resp->status == __HTTP_STATUS_HANDLED) {
    return;
  }
  bool has_content_length = false;
  if (resp->body != NULL) {
    if (resp->headers_len > 0) {
      for (int i = 0; i < resp->headers_len; i++) {
        http_header_t *header = &resp->headers[i];
        if (strcasecmp(header->key, "Content-Length") == 0) {
          has_content_length = true;
          break;
        }
      }
    }
    if (!has_content_length) {
      char content_length[50];
      snprintf(content_length, 50, "%ld", resp->body_len);
      http_resp_header(resp, (char *) "Content-Length", content_length);
    }
  }
  http_resp_write_head(resp, conn);
  http_resp_write_body(resp, conn);
}

http_err_t http_bind(http_t *self, char *hostname, int port, http_host_t *hosts, int hosts_len) {
  return sock_bind(self->sock, hostname, port, hosts, hosts_len);
}

http_err_t http_listen(http_t *self) {
  return sock_listen(self->sock);
}

http_err_t http_bind_listen(http_t *self, char *hostname, int port) {
  return sock_bind_listen(self->sock, hostname, port);
}

void http_close(http_t *self) {
  sock_close(self->sock);
}

#endif // SO_HTTP_IMPL
#endif // _SO_HTTP_H
