/*
  This file is part of TALER
  Copyright (C) 2024, 2025 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_get.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_CharityGetHandle
{
  /**
   * 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_GetCharityResponseCallback cb;

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

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

};

/**
 * Decode the JSON in @a resp_obj from the /charities/$ID response
 * and store the data in the @a charity_data.
 *
 * @param[in] resp_obj JSON object to parse
 * @param[out] charity_data where to store the results we decoded
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
 * (malformed JSON)
 */
static enum GNUNET_GenericReturnValue
handle_charity_get_ok (const json_t *resp_obj,
                       struct DONAU_CharityGetHandle *cgh,
                       struct DONAU_GetCharityResponse *gcresp)
{
  struct DONAU_Charity *charity = &gcresp->details.ok.charity;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_fixed_auto ("charity_pub",
                                 &charity->charity_pub),
    GNUNET_JSON_spec_string ("name",
                             &charity->name),
    GNUNET_JSON_spec_string ("url",
                             &charity->charity_url),
    TALER_JSON_spec_amount_any ("max_per_year",
                                &charity->max_per_year),
    TALER_JSON_spec_amount_any ("receipts_to_date",
                                &charity->receipts_to_date),
    GNUNET_JSON_spec_uint64 ("current_year",
                             &charity->current_year),
    GNUNET_JSON_spec_end ()
  };

  if (GNUNET_OK !=
      GNUNET_JSON_parse (resp_obj,
                         spec,
                         NULL,
                         NULL))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  cgh->cb (cgh->cb_cls,
           gcresp);
  cgh->cb = NULL;
  return GNUNET_OK;
}


/**
 * 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_get_finished (void *cls,
                             long response_code,
                             const void *resp_obj)
{
  struct DONAU_CharityGetHandle *cgh = cls;
  const json_t *j = resp_obj;
  struct DONAU_GetCharityResponse gcresp = {
    .hr.reply = j,
    .hr.http_status = (unsigned int) response_code
  };

  cgh->job = NULL;
  switch (response_code)
  {
  case 0:
    gcresp.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_OK:
    if (GNUNET_OK !=
        handle_charity_get_ok (j,
                               cgh,
                               &gcresp))
    {
      gcresp.hr.http_status = 0;
      gcresp.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
    }
    break;
  case MHD_HTTP_BAD_REQUEST:
    /* This should never happen, either us or the donau is buggy
       (or API version conflict); just pass JSON reply to the application */
    gcresp.hr.ec = TALER_JSON_get_error_code (j);
    gcresp.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  case MHD_HTTP_FORBIDDEN:
    /* Nothing really to verify */
    gcresp.hr.ec = TALER_JSON_get_error_code (j);
    gcresp.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  case MHD_HTTP_NOT_FOUND:
    /* Nothing really to verify, this should never
       happen, we should pass the JSON reply to the application */
    gcresp.hr.ec = TALER_JSON_get_error_code (j);
    gcresp.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    /* Server had an internal issue; we should retry, but this API
       leaves this to the application */
    gcresp.hr.ec = TALER_JSON_get_error_code (j);
    gcresp.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  default:
    /* unexpected response code */
    GNUNET_break_op (0);
    gcresp.hr.ec = TALER_JSON_get_error_code (j);
    gcresp.hr.hint = TALER_JSON_get_error_hint (j);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d for GET %s\n",
                (unsigned int) response_code,
                (int) gcresp.hr.ec,
                cgh->url);
    break;
  }
  if (NULL != cgh->cb)
  {
    cgh->cb (cgh->cb_cls,
             &gcresp);
    cgh->cb = NULL;
  }
  DONAU_charity_get_cancel (cgh);
}


struct DONAU_CharityGetHandle *
DONAU_charity_get (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const uint64_t id,
  const struct DONAU_CharityPrivateKeyP *charity_priv,
  DONAU_GetCharityResponseCallback cb,
  void *cb_cls)
{
  struct DONAU_CharityGetHandle *cgh;
  CURL *eh;
  char arg_str[sizeof (id) * 2 + 32];

  TALER_LOG_DEBUG ("Connecting to the donau (%s)\n",
                   url);
  cgh = GNUNET_new (struct DONAU_CharityGetHandle);
  cgh->cb = cb;
  cgh->charity_id = id;
  cgh->cb_cls = cb_cls;
  GNUNET_snprintf (arg_str,
                   sizeof (arg_str),
                   "charity/%llu",
                   (unsigned long long)
                   id);
  cgh->url = TALER_url_join (url,
                             arg_str,
                             NULL);
  if (NULL == cgh->url)
  {
    GNUNET_free (cgh);
    return NULL;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Requesting a charity with URL `%s'.\n",
              cgh->url);
  eh = DONAU_curl_easy_get_ (cgh->url);
  if (NULL == eh)
  {
    GNUNET_break (0);
    GNUNET_free (cgh->url);
    GNUNET_free (cgh);
    return NULL;
  }
  cgh->job = GNUNET_CURL_job_add_with_ct_json (ctx,
                                               eh,
                                               &handle_charity_get_finished,
                                               cgh);
  GNUNET_assert (NULL != cgh->job);
  {
    struct DONAU_CharitySignatureP charity_sig;
    char *sig_hdr;
    char *hdr;
    struct curl_slist *auth;

    DONAU_charity_get_info_sign (charity_priv,
                                 &charity_sig);

    sig_hdr = GNUNET_STRINGS_data_to_string_alloc (
      &charity_sig,
      sizeof (charity_sig));
    GNUNET_asprintf (&hdr,
                     "%s: %s",
                     DONAU_HTTP_HEADER_CHARITY_SIGNATURE,
                     sig_hdr);
    GNUNET_free (sig_hdr);
    auth = curl_slist_append (NULL,
                              hdr);
    GNUNET_free (hdr);
    GNUNET_CURL_extend_headers (cgh->job,
                                auth);
    curl_slist_free_all (auth);
  }

  return cgh;
}


void
DONAU_charity_get_cancel (
  struct DONAU_CharityGetHandle *cgh)
{
  if (NULL != cgh->job)
  {
    GNUNET_CURL_job_cancel (cgh->job);
    cgh->job = NULL;
  }
  GNUNET_free (cgh->url);
  GNUNET_free (cgh);
}
