// Written by retoor@molodetz.nl

// This code defines a simple HTTP client using libcurl in C. It provides
// functions for executing POST and GET HTTP requests with JSON data, including
// authorization via a bearer token. The functions `curl_post` and `curl_get`
// handle these operations and return the server's response as a string.

// Uses libcurl for HTTP requests and includes a custom "auth.h" for API key
// resolution.

// MIT License
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: the above copyright
// notice and this permission notice shall be included in all copies or
// substantial portions of the Software. The Software is provided "as is",
// without warranty of any kind, express or implied, including but not limited
// to the warranties of merchantability, fitness for a particular purpose and
// noninfringement. In no event shall the authors or copyright holders be liable
// for any claim, damages or other liability, whether in an action of contract,
// tort or otherwise, arising from, out of or in connection with the software or
// the use or other dealings in the Software.

#ifndef HTTP_CURL
#define HTTP_CURL

#include "auth.h"
#include <curl/curl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct ResponseBuffer {
  char *data;
  size_t size;
};

static size_t WriteCallback(void *contents, size_t size, size_t nmemb,
                            void *userp) {
  size_t total_size = size * nmemb;
  struct ResponseBuffer *response = (struct ResponseBuffer *)userp;
  char *ptr = realloc(response->data, response->size + total_size + 1);
  if (ptr == NULL) {
    fprintf(stderr, "Failed to allocate memory for response\n");
    return 0;
  }
  response->data = ptr;
  memcpy(&(response->data[response->size]), contents, total_size);
  response->size += total_size;
  response->data[response->size] = '\0';
  return total_size;
}

char *curl_post(const char *url, const char *data) {
  CURL *curl;
  CURLcode res;
  struct ResponseBuffer response = {malloc(1), 0};

  if (!response.data)
    return NULL;

  curl = curl_easy_init();
  if (curl) {
    struct curl_slist *headers = NULL;
    curl_easy_setopt(curl, CURLOPT_URL, url);
    headers = curl_slist_append(headers, "Content-Type: application/json");
    char bearer_header[1337];
    sprintf(bearer_header, "Authorization: Bearer %s", resolve_api_key());
    headers = curl_slist_append(headers, bearer_header);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);
    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
      fprintf(stderr, "Url: %s\n", data);
      fprintf(stderr, "Data: %s\n", data);
      fprintf(stderr, "An error occurred: %s\n", curl_easy_strerror(res));
    }
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    return response.data;
  }
  return NULL;
}

char *curl_get(const char *url) {
  CURL *curl;
  CURLcode res;
  struct ResponseBuffer response = {malloc(1), 0};

  if (!response.data)
    return NULL;

  curl = curl_easy_init();
  if (curl) {
    struct curl_slist *headers = NULL;
    curl_easy_setopt(curl, CURLOPT_URL, url);
    headers = curl_slist_append(headers, "Content-Type: application/json");
    char bearer_header[1337];
    sprintf(bearer_header, "Authorization: Bearer %s", resolve_api_key());
    headers = curl_slist_append(headers, bearer_header);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);
    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
      fprintf(stderr, "An error occurred: %s\n", curl_easy_strerror(res));
    }
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
  }
  return response.data;
}

#endif
