/*
  This file is part of TALER
  Copyright (C) 2020-2026 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/exchange_api_post-management-global-fees.c
 * @brief functions to set global fees at an exchange
 * @author Christian Grothoff
 */
#include "taler/taler_json_lib.h"
#include <gnunet/gnunet_curl_lib.h>
#include <microhttpd.h>
#include "taler/exchange/post-management-global-fees.h"
#include "exchange_api_curl_defaults.h"
#include "taler/taler_curl_lib.h"


struct TALER_EXCHANGE_PostManagementGlobalFeesHandle
{

  /**
   * The base URL for this request.
   */
  char *base_url;

  /**
   * The full URL for this request, set during _start.
   */
  char *url;

  /**
   * Minor context that holds body and headers.
   */
  struct TALER_CURL_PostContext post_ctx;

  /**
   * Handle for the request.
   */
  struct GNUNET_CURL_Job *job;

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

  /**
   * Closure for @a cb.
   */
  TALER_EXCHANGE_POST_MANAGEMENT_GLOBAL_FEES_RESULT_CLOSURE *cb_cls;

  /**
   * Reference to the execution context.
   */
  struct GNUNET_CURL_Context *ctx;

  /**
   * Start of validity period.
   */
  struct GNUNET_TIME_Timestamp validity_start;

  /**
   * End of validity period.
   */
  struct GNUNET_TIME_Timestamp validity_end;

  /**
   * Global fees for this time period.
   */
  struct TALER_GlobalFeeSet fees;

  /**
   * When do purses time out.
   */
  struct GNUNET_TIME_Relative purse_timeout;

  /**
   * How long are account histories preserved.
   */
  struct GNUNET_TIME_Relative history_expiration;

  /**
   * How many purses are free per account.
   */
  uint32_t purse_account_limit;

  /**
   * Signature affirming the global fees.
   */
  struct TALER_MasterSignatureP master_sig;

};


/**
 * Function called when we're done processing the
 * HTTP POST /management/global-fees request.
 *
 * @param cls the `struct TALER_EXCHANGE_PostManagementGlobalFeesHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_global_fees_finished (void *cls,
                             long response_code,
                             const void *response)
{
  struct TALER_EXCHANGE_PostManagementGlobalFeesHandle *pmgfh = cls;
  const json_t *json = response;
  struct TALER_EXCHANGE_PostManagementGlobalFeesResponse res = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  pmgfh->job = NULL;
  switch (response_code)
  {
  case MHD_HTTP_NO_CONTENT:
    break;
  case MHD_HTTP_FORBIDDEN:
    res.hr.ec = TALER_JSON_get_error_code (json);
    res.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_CONFLICT:
    res.hr.ec = TALER_JSON_get_error_code (json);
    res.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_CONTENT_TOO_LARGE:
    res.hr.ec = TALER_JSON_get_error_code (json);
    res.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    /* unexpected response code */
    GNUNET_break_op (0);
    res.hr.ec = TALER_JSON_get_error_code (json);
    res.hr.hint = TALER_JSON_get_error_hint (json);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d for exchange management set global fee\n",
                (unsigned int) response_code,
                (int) res.hr.ec);
    break;
  }
  if (NULL != pmgfh->cb)
  {
    pmgfh->cb (pmgfh->cb_cls,
               &res);
    pmgfh->cb = NULL;
  }
  TALER_EXCHANGE_post_management_global_fees_cancel (pmgfh);
}


struct TALER_EXCHANGE_PostManagementGlobalFeesHandle *
TALER_EXCHANGE_post_management_global_fees_create (
  struct GNUNET_CURL_Context *ctx,
  const char *exchange_base_url,
  struct GNUNET_TIME_Timestamp validity_start,
  struct GNUNET_TIME_Timestamp validity_end,
  const struct TALER_GlobalFeeSet *fees,
  struct GNUNET_TIME_Relative purse_timeout,
  struct GNUNET_TIME_Relative history_expiration,
  uint32_t purse_account_limit,
  const struct TALER_MasterSignatureP *master_sig)
{
  struct TALER_EXCHANGE_PostManagementGlobalFeesHandle *pmgfh;

  pmgfh = GNUNET_new (struct TALER_EXCHANGE_PostManagementGlobalFeesHandle);
  pmgfh->ctx = ctx;
  pmgfh->base_url = GNUNET_strdup (exchange_base_url);
  pmgfh->validity_start = validity_start;
  pmgfh->validity_end = validity_end;
  pmgfh->fees = *fees;
  pmgfh->purse_timeout = purse_timeout;
  pmgfh->history_expiration = history_expiration;
  pmgfh->purse_account_limit = purse_account_limit;
  pmgfh->master_sig = *master_sig;
  return pmgfh;
}


enum TALER_ErrorCode
TALER_EXCHANGE_post_management_global_fees_start (
  struct TALER_EXCHANGE_PostManagementGlobalFeesHandle *pmgfh,
  TALER_EXCHANGE_PostManagementGlobalFeesCallback cb,
  TALER_EXCHANGE_POST_MANAGEMENT_GLOBAL_FEES_RESULT_CLOSURE *cb_cls)
{
  CURL *eh;
  json_t *body;

  pmgfh->cb = cb;
  pmgfh->cb_cls = cb_cls;
  pmgfh->url = TALER_url_join (pmgfh->base_url,
                               "management/global-fee",
                               NULL);
  if (NULL == pmgfh->url)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Could not construct request URL.\n");
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  }
  body = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_data_auto ("master_sig",
                                &pmgfh->master_sig),
    GNUNET_JSON_pack_timestamp ("fee_start",
                                pmgfh->validity_start),
    GNUNET_JSON_pack_timestamp ("fee_end",
                                pmgfh->validity_end),
    TALER_JSON_pack_amount ("history_fee",
                            &pmgfh->fees.history),
    TALER_JSON_pack_amount ("account_fee",
                            &pmgfh->fees.account),
    TALER_JSON_pack_amount ("purse_fee",
                            &pmgfh->fees.purse),
    GNUNET_JSON_pack_time_rel ("purse_timeout",
                               pmgfh->purse_timeout),
    GNUNET_JSON_pack_time_rel ("history_expiration",
                               pmgfh->history_expiration),
    GNUNET_JSON_pack_uint64 ("purse_account_limit",
                             pmgfh->purse_account_limit));
  eh = TALER_EXCHANGE_curl_easy_get_ (pmgfh->url);
  if ( (NULL == eh) ||
       (GNUNET_OK !=
        TALER_curl_easy_post (&pmgfh->post_ctx,
                              eh,
                              body)) )
  {
    GNUNET_break (0);
    if (NULL != eh)
      curl_easy_cleanup (eh);
    json_decref (body);
    GNUNET_free (pmgfh->url);
    pmgfh->url = NULL;
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  json_decref (body);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Requesting URL '%s'\n",
              pmgfh->url);
  pmgfh->job = GNUNET_CURL_job_add2 (pmgfh->ctx,
                                     eh,
                                     pmgfh->post_ctx.headers,
                                     &handle_global_fees_finished,
                                     pmgfh);
  if (NULL == pmgfh->job)
  {
    GNUNET_break (0);
    TALER_curl_easy_post_finished (&pmgfh->post_ctx);
    GNUNET_free (pmgfh->url);
    pmgfh->url = NULL;
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  return TALER_EC_NONE;
}


void
TALER_EXCHANGE_post_management_global_fees_cancel (
  struct TALER_EXCHANGE_PostManagementGlobalFeesHandle *pmgfh)
{
  if (NULL != pmgfh->job)
  {
    GNUNET_CURL_job_cancel (pmgfh->job);
    pmgfh->job = NULL;
  }
  TALER_curl_easy_post_finished (&pmgfh->post_ctx);
  GNUNET_free (pmgfh->url);
  GNUNET_free (pmgfh->base_url);
  GNUNET_free (pmgfh);
}


/* end of exchange_api_post-management-global-fees.c */
