/*
  This file is part of TALER
  Copyright (C) 2021-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-kyc-wallet.c
 * @brief Implementation of the /kyc-wallet request
 * @author Christian Grothoff
 */
#include <microhttpd.h> /* just for HTTP status codes */
#include <gnunet/gnunet_util_lib.h>
#include <gnunet/gnunet_curl_lib.h>
#include "taler/taler_json_lib.h"
#include "taler/exchange/post-kyc-wallet.h"
#include "taler/taler_signatures.h"
#include "exchange_api_curl_defaults.h"
#include "taler/taler_curl_lib.h"


/**
 * @brief A POST /kyc-wallet handle
 */
struct TALER_EXCHANGE_PostKycWalletHandle
{

  /**
   * Context for curl easy post. Keeps the data that must
   * persist for Curl to make the upload.
   */
  struct TALER_CURL_PostContext post_ctx;

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

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

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

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

  /**
   * Closure for @e cb.
   */
  TALER_EXCHANGE_POST_KYC_WALLET_RESULT_CLOSURE *cb_cls;

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

  /**
   * Reserve private key of the wallet.
   */
  struct TALER_ReservePrivateKeyP reserve_priv;

  /**
   * Balance (or balance threshold) crossed by the wallet.
   */
  struct TALER_Amount balance;

};


/**
 * Function called when we're done processing the
 * HTTP /kyc-wallet request.
 *
 * @param cls the `struct TALER_EXCHANGE_PostKycWalletHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response parsed JSON result, NULL on error
 */
static void
handle_kyc_wallet_finished (void *cls,
                            long response_code,
                            const void *response)
{
  struct TALER_EXCHANGE_PostKycWalletHandle *pkwh = cls;
  const json_t *j = response;
  struct TALER_EXCHANGE_PostKycWalletResponse ks = {
    .hr.reply = j,
    .hr.http_status = (unsigned int) response_code
  };

  pkwh->job = NULL;
  switch (response_code)
  {
  case 0:
    ks.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_OK:
    {
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_mark_optional (
          TALER_JSON_spec_amount_any (
            "next_threshold",
            &ks.details.ok.next_threshold),
          NULL),
        GNUNET_JSON_spec_timestamp (
          "expiration_time",
          &ks.details.ok.expiration_time),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (j,
                             spec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        ks.hr.http_status = 0;
        ks.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
      break;
    }
  case MHD_HTTP_NO_CONTENT:
    break;
  case MHD_HTTP_BAD_REQUEST:
    ks.hr.ec = TALER_JSON_get_error_code (j);
    /* This should never happen, either us or the exchange is buggy
       (or API version conflict); just pass JSON reply to the application */
    break;
  case MHD_HTTP_FORBIDDEN:
    ks.hr.ec = TALER_JSON_get_error_code (j);
    break;
  case MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS:
    ks.hr.ec = TALER_JSON_get_error_code (j);
    ks.hr.hint = TALER_JSON_get_error_hint (j);
    if (GNUNET_OK !=
        TALER_EXCHANGE_parse_451 (&ks.details.unavailable_for_legal_reasons,
                                  j))
    {
      GNUNET_break_op (0);
      ks.hr.http_status = 0;
      ks.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
      break;
    }
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    ks.hr.ec = TALER_JSON_get_error_code (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);
    ks.hr.ec = TALER_JSON_get_error_code (j);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d for exchange /kyc-wallet\n",
                (unsigned int) response_code,
                (int) ks.hr.ec);
    break;
  }
  if (NULL != pkwh->cb)
  {
    pkwh->cb (pkwh->cb_cls,
              &ks);
    pkwh->cb = NULL;
  }
  TALER_EXCHANGE_post_kyc_wallet_cancel (pkwh);
}


struct TALER_EXCHANGE_PostKycWalletHandle *
TALER_EXCHANGE_post_kyc_wallet_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const struct TALER_ReservePrivateKeyP *reserve_priv,
  const struct TALER_Amount *balance)
{
  struct TALER_EXCHANGE_PostKycWalletHandle *pkwh;

  pkwh = GNUNET_new (struct TALER_EXCHANGE_PostKycWalletHandle);
  pkwh->ctx = ctx;
  pkwh->base_url = GNUNET_strdup (url);
  pkwh->reserve_priv = *reserve_priv;
  pkwh->balance = *balance;
  return pkwh;
}


enum TALER_ErrorCode
TALER_EXCHANGE_post_kyc_wallet_start (
  struct TALER_EXCHANGE_PostKycWalletHandle *pkwh,
  TALER_EXCHANGE_PostKycWalletCallback cb,
  TALER_EXCHANGE_POST_KYC_WALLET_RESULT_CLOSURE *cb_cls)
{
  CURL *eh;
  json_t *req;
  struct TALER_ReservePublicKeyP reserve_pub;
  struct TALER_ReserveSignatureP reserve_sig;

  pkwh->cb = cb;
  pkwh->cb_cls = cb_cls;
  GNUNET_CRYPTO_eddsa_key_get_public (&pkwh->reserve_priv.eddsa_priv,
                                      &reserve_pub.eddsa_pub);
  TALER_wallet_account_setup_sign (&pkwh->reserve_priv,
                                   &pkwh->balance,
                                   &reserve_sig);
  req = GNUNET_JSON_PACK (
    TALER_JSON_pack_amount ("balance",
                            &pkwh->balance),
    GNUNET_JSON_pack_data_auto ("reserve_pub",
                                &reserve_pub),
    GNUNET_JSON_pack_data_auto ("reserve_sig",
                                &reserve_sig));
  GNUNET_assert (NULL != req);
  pkwh->url = TALER_url_join (pkwh->base_url,
                              "kyc-wallet",
                              NULL);
  if (NULL == pkwh->url)
  {
    json_decref (req);
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  }
  eh = TALER_EXCHANGE_curl_easy_get_ (pkwh->url);
  if ( (NULL == eh) ||
       (GNUNET_OK !=
        TALER_curl_easy_post (&pkwh->post_ctx,
                              eh,
                              req)) )
  {
    GNUNET_break (0);
    if (NULL != eh)
      curl_easy_cleanup (eh);
    json_decref (req);
    GNUNET_free (pkwh->url);
    pkwh->url = NULL;
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  json_decref (req);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Requesting URL '%s'\n",
              pkwh->url);
  pkwh->job = GNUNET_CURL_job_add2 (pkwh->ctx,
                                    eh,
                                    pkwh->post_ctx.headers,
                                    &handle_kyc_wallet_finished,
                                    pkwh);
  if (NULL == pkwh->job)
  {
    TALER_curl_easy_post_finished (&pkwh->post_ctx);
    GNUNET_free (pkwh->url);
    pkwh->url = NULL;
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  return TALER_EC_NONE;
}


void
TALER_EXCHANGE_post_kyc_wallet_cancel (
  struct TALER_EXCHANGE_PostKycWalletHandle *pkwh)
{
  if (NULL != pkwh->job)
  {
    GNUNET_CURL_job_cancel (pkwh->job);
    pkwh->job = NULL;
  }
  TALER_curl_easy_post_finished (&pkwh->post_ctx);
  GNUNET_free (pkwh->url);
  GNUNET_free (pkwh->base_url);
  GNUNET_free (pkwh);
}


/* end of exchange_api_post-kyc-wallet.c */
