/*
  This file is part of TALER
  Copyright (C) 2024 Taler Systems SA

  TALER 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, or (at your
  option) any later version.

  TALER 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 TALER; see the file COPYING.  If not, see
  <http://www.gnu.org/licenses/>
*/

/**
 * @file lib/donau_api_charity_delete.c
 * @brief Implementation of the "handle" component of the donau's HTTP API
 * @author Lukas Matyja
 */
#include <gnunet/gnunet_curl_lib.h>
#include <taler/taler_json_lib.h>
#include "donau_service.h"
#include "donau_api_curl_defaults.h"
#include "donau_json_lib.h"


/**
 * Handle for a GET /charities/$CHARITY_ID request.
 */
struct DONAU_CharityDeleteHandle
{
  /**
   * The url for the /charities/$CHARITY_ID request.
   */
  char *url;

  /**
   * Entry for this request with the `struct GNUNET_CURL_Context`.
   */
  struct GNUNET_CURL_Job *job;

  /**
   * Function to call with the result.
   */
  DONAU_DeleteCharityResponseCallback cb;

  /**
   * Charity id we are querying.
   */
  unsigned long long charity_id;

  /**
   * Closure to pass to @e cb.
   */
  void *cb_cls;

};


/**
 * Callback used when downloading the reply to a /charity request
 * is complete.
 *
 * @param cls the `struct KeysRequest`
 * @param response_code HTTP response code, 0 on error
 * @param resp_obj parsed JSON result, NULL on error
 */
static void
handle_charity_delete_finished (void *cls,
                                long response_code,
                                const void *resp_obj)
{
  struct DONAU_CharityDeleteHandle *cdh = cls;
  const json_t *j = resp_obj;
  struct DONAU_DeleteCharityResponse dcresp = {
    .hr.reply = j,
    .hr.http_status = (unsigned int) response_code
  };

  cdh->job = NULL;
  switch (response_code)
  {
  case 0:
    dcresp.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_NO_CONTENT:
    break;
  case MHD_HTTP_BAD_REQUEST:
    /* This should never happen, either us or the exchange is buggy
       (or API version conflict); just pass JSON reply to the application */
    dcresp.hr.ec = TALER_JSON_get_error_code (j);
    dcresp.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  case MHD_HTTP_FORBIDDEN:
    dcresp.hr.ec = TALER_JSON_get_error_code (j);
    dcresp.hr.hint = TALER_JSON_get_error_hint (j);
    /* Nothing really to verify, exchange says one of the signatures is
       invalid; as we checked them, this should never happen, we
       should pass the JSON reply to the application */
    break;
  case MHD_HTTP_NOT_FOUND:
    dcresp.hr.ec = TALER_JSON_get_error_code (j);
    dcresp.hr.hint = TALER_JSON_get_error_hint (j);
    /* Nothing really to verify, this should never
       happen, we should pass the JSON reply to the application */
    break;
  case MHD_HTTP_CONFLICT:
    dcresp.hr.ec = TALER_JSON_get_error_code (j);
    dcresp.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    dcresp.hr.ec = TALER_JSON_get_error_code (j);
    dcresp.hr.hint = TALER_JSON_get_error_hint (j);
    /* Server had an internal issue; we should retry, but this API
       leaves this to the application */
    break;
  default:
    /* unexpected response code */
    GNUNET_break_op (0);
    dcresp.hr.ec = TALER_JSON_get_error_code (j);
    dcresp.hr.hint = TALER_JSON_get_error_hint (j);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d for DELETE %s\n",
                (unsigned int) response_code,
                (int) dcresp.hr.ec,
                cdh->url);
    break;
  }
  if (NULL != cdh->cb)
  {
    cdh->cb (cdh->cb_cls,
             &dcresp);
    cdh->cb = NULL;
  }
  DONAU_charity_delete_cancel (cdh);
}


struct DONAU_CharityDeleteHandle *
DONAU_charity_delete (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const uint64_t id,
  const struct DONAU_BearerToken *bearer,
  DONAU_DeleteCharityResponseCallback cb,
  void *cb_cls)
{
  struct DONAU_CharityDeleteHandle *cdh;
  CURL *eh;
  char arg_str[sizeof (id) * 2 + 32];

  TALER_LOG_DEBUG ("Connecting to the donau (%s)\n",
                   url);
  cdh = GNUNET_new (struct DONAU_CharityDeleteHandle);
  cdh->url = GNUNET_strdup (url);
  cdh->cb = cb;
  cdh->charity_id = id;
  cdh->cb_cls = cb_cls;
  GNUNET_snprintf (arg_str,
                   sizeof (arg_str),
                   "charities/%llu",
                   (unsigned long long)
                   id);
  cdh->url = TALER_url_join (url,
                             arg_str,
                             NULL);
  if (NULL == cdh->url)
  {
    GNUNET_free (cdh);
    return NULL;
  }
  eh = DONAU_curl_easy_get_ (cdh->url);
  if (NULL == eh)
  {
    GNUNET_break (0);
    GNUNET_free (cdh->url);
    GNUNET_free (cdh);
    return NULL;
  }
  GNUNET_assert (CURLE_OK ==
                 curl_easy_setopt (eh,
                                   CURLOPT_CUSTOMREQUEST,
                                   MHD_HTTP_METHOD_DELETE));
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Requesting charity deletion with URL `%s'.\n",
              cdh->url);
  cdh->job = GNUNET_CURL_job_add_with_ct_json (ctx,
                                               eh,
                                               &handle_charity_delete_finished,
                                               cdh);
  GNUNET_assert (NULL != cdh->job);
  if (NULL != bearer)
  {
    struct curl_slist *auth;
    char *hdr;

    GNUNET_asprintf (&hdr,
                     "%s: Bearer %s",
                     MHD_HTTP_HEADER_AUTHORIZATION,
                     bearer->token);
    auth = curl_slist_append (NULL,
                              hdr);
    GNUNET_free (hdr);
    GNUNET_CURL_extend_headers (cdh->job,
                                auth);
    curl_slist_free_all (auth);
  }
  return cdh;
}


void
DONAU_charity_delete_cancel (
  struct DONAU_CharityDeleteHandle *cdh)
{
  if (NULL != cdh->job)
  {
    GNUNET_CURL_job_cancel (cdh->job);
    cdh->job = NULL;
  }
  GNUNET_free (cdh->url);
  GNUNET_free (cdh);
}
