/*
  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_get-kyc-check-H_NORMALIZED_PAYTO.c
 * @brief Implementation of the /kyc-check request
 * @author Christian Grothoff
 */
#include "platform.h"  /* UNNECESSARY? */
#include <microhttpd.h> /* just for HTTP check codes */
#include <gnunet/gnunet_util_lib.h>
#include <gnunet/gnunet_curl_lib.h>
#include "taler/taler_exchange_service.h"  /* UNNECESSARY? */
#include "taler/taler_json_lib.h"
#include "taler/exchange/get-kyc-check-H_NORMALIZED_PAYTO.h"
#include "taler/taler_signatures.h"
#include "exchange_api_curl_defaults.h"


/**
 * @brief A GET /kyc-check/$H_NORMALIZED_PAYTO handle
 */
struct TALER_EXCHANGE_GetKycCheckHandle
{

  /**
   * 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_GetKycCheckCallback cb;

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

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

  /**
   * Hash of the payto URI we are checking.
   */
  struct TALER_NormalizedPaytoHashP h_payto;

  /**
   * Private key to authorize the request.
   */
  union TALER_AccountPrivateKeyP account_priv;

  /**
   * Long polling target.
   */
  enum TALER_EXCHANGE_KycLongPollTarget lpt;

  /**
   * Latest known rule generation (for long polling).
   */
  uint64_t known_rule_gen;

  /**
   * Long polling timeout.
   */
  struct GNUNET_TIME_Relative timeout;

};


/**
 * Parse an account KYC status from JSON and invoke the callback.
 *
 * @param[in,out] gkch handle
 * @param j JSON to parse
 * @param res response to fill
 * @param status account status field within @a res to fill
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_account_status (
  struct TALER_EXCHANGE_GetKycCheckHandle *gkch,
  const json_t *j,
  struct TALER_EXCHANGE_GetKycCheckResponse *res,
  struct TALER_EXCHANGE_AccountKycStatus *status)
{
  const json_t *limits = NULL;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_bool ("aml_review",
                           &status->aml_review),
    GNUNET_JSON_spec_uint64 ("rule_gen",
                             &status->rule_gen),
    GNUNET_JSON_spec_fixed_auto ("access_token",
                                 &status->access_token),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("tos_required",
                               &status->tos_required),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_array_const ("limits",
                                    &limits),
      NULL),
    GNUNET_JSON_spec_end ()
  };

  if (GNUNET_OK !=
      GNUNET_JSON_parse (j,
                         spec,
                         NULL, NULL))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if ( (NULL != limits) &&
       (0 != json_array_size (limits)) )
  {
    size_t limit_length = json_array_size (limits);
    struct TALER_EXCHANGE_AccountLimit ala[GNUNET_NZL (limit_length)];
    size_t i;
    json_t *limit;

    json_array_foreach (limits, i, limit)
    {
      struct TALER_EXCHANGE_AccountLimit *al = &ala[i];
      struct GNUNET_JSON_Specification ispec[] = {
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_bool ("soft_limit",
                                 &al->soft_limit),
          NULL),
        GNUNET_JSON_spec_relative_time ("timeframe",
                                        &al->timeframe),
        TALER_JSON_spec_kycte ("operation_type",
                               &al->operation_type),
        TALER_JSON_spec_amount_any ("threshold",
                                    &al->threshold),
        GNUNET_JSON_spec_end ()
      };

      al->soft_limit = false;
      if (GNUNET_OK !=
          GNUNET_JSON_parse (limit,
                             ispec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        return GNUNET_SYSERR;
      }
    }
    status->limits = ala;
    status->limits_length = limit_length;
    gkch->cb (gkch->cb_cls,
              res);
  }
  else
  {
    gkch->cb (gkch->cb_cls,
              res);
  }
  GNUNET_JSON_parse_free (spec);
  return GNUNET_OK;
}


/**
 * Function called when we're done processing the
 * HTTP GET /kyc-check/$H_NORMALIZED_PAYTO request.
 *
 * @param cls the `struct TALER_EXCHANGE_GetKycCheckHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response parsed JSON result, NULL on error
 */
static void
handle_kyc_check_finished (void *cls,
                           long response_code,
                           const void *response)
{
  struct TALER_EXCHANGE_GetKycCheckHandle *gkch = cls;
  const json_t *j = response;
  struct TALER_EXCHANGE_GetKycCheckResponse ks = {
    .hr.reply = j,
    .hr.http_status = (unsigned int) response_code
  };

  gkch->job = NULL;
  switch (response_code)
  {
  case 0:
    ks.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_OK:
    {
      if (GNUNET_OK !=
          parse_account_status (gkch,
                                j,
                                &ks,
                                &ks.details.ok))
      {
        GNUNET_break_op (0);
        ks.hr.http_status = 0;
        ks.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
      TALER_EXCHANGE_get_kyc_check_cancel (gkch);
      return;
    }
  case MHD_HTTP_ACCEPTED:
    {
      if (GNUNET_OK !=
          parse_account_status (gkch,
                                j,
                                &ks,
                                &ks.details.accepted))
      {
        GNUNET_break_op (0);
        ks.hr.http_status = 0;
        ks.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
      TALER_EXCHANGE_get_kyc_check_cancel (gkch);
      return;
    }
  case MHD_HTTP_NO_CONTENT:
    break;
  case MHD_HTTP_BAD_REQUEST:
    ks.hr.ec = TALER_JSON_get_error_code (j);
    break;
  case MHD_HTTP_FORBIDDEN:
    {
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_fixed_auto (
          "expected_account_pub",
          &ks.details.forbidden.expected_account_pub),
        TALER_JSON_spec_ec ("code",
                            &ks.hr.ec),
        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_NOT_FOUND:
    ks.hr.ec = TALER_JSON_get_error_code (j);
    break;
  case MHD_HTTP_CONFLICT:
    ks.hr.ec = TALER_JSON_get_error_code (j);
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    ks.hr.ec = TALER_JSON_get_error_code (j);
    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_check\n",
                (unsigned int) response_code,
                (int) ks.hr.ec);
    break;
  }
  if (NULL != gkch->cb)
  {
    gkch->cb (gkch->cb_cls,
              &ks);
    gkch->cb = NULL;
  }
  TALER_EXCHANGE_get_kyc_check_cancel (gkch);
}


struct TALER_EXCHANGE_GetKycCheckHandle *
TALER_EXCHANGE_get_kyc_check_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const struct TALER_NormalizedPaytoHashP *h_payto,
  const union TALER_AccountPrivateKeyP *pk)
{
  struct TALER_EXCHANGE_GetKycCheckHandle *gkch;

  gkch = GNUNET_new (struct TALER_EXCHANGE_GetKycCheckHandle);
  gkch->ctx = ctx;
  gkch->base_url = GNUNET_strdup (url);
  gkch->h_payto = *h_payto;
  gkch->account_priv = *pk;
  return gkch;
}


enum GNUNET_GenericReturnValue
TALER_EXCHANGE_get_kyc_check_set_options_ (
  struct TALER_EXCHANGE_GetKycCheckHandle *gkch,
  unsigned int num_options,
  const struct TALER_EXCHANGE_GetKycCheckOptionValue *options)
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    const struct TALER_EXCHANGE_GetKycCheckOptionValue *opt = &options[i];

    switch (opt->option)
    {
    case TALER_EXCHANGE_GET_KYC_CHECK_OPTION_END:
      return GNUNET_OK;
    case TALER_EXCHANGE_GET_KYC_CHECK_OPTION_KNOWN_RULE_GEN:
      gkch->known_rule_gen = opt->details.known_rule_gen;
      break;
    case TALER_EXCHANGE_GET_KYC_CHECK_OPTION_LPT:
      gkch->lpt = opt->details.lpt;
      break;
    case TALER_EXCHANGE_GET_KYC_CHECK_OPTION_TIMEOUT:
      gkch->timeout = opt->details.timeout;
      break;
    default:
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_EXCHANGE_get_kyc_check_start (
  struct TALER_EXCHANGE_GetKycCheckHandle *gkch,
  TALER_EXCHANGE_GetKycCheckCallback cb,
  TALER_EXCHANGE_GET_KYC_CHECK_RESULT_CLOSURE *cb_cls)
{
  CURL *eh;
  char arg_str[128];
  char timeout_ms[32];
  char lpt_str[32];
  char krg_str[32];
  struct curl_slist *job_headers = NULL;
  unsigned long long tms;

  gkch->cb = cb;
  gkch->cb_cls = cb_cls;
  {
    char *hps;

    hps = GNUNET_STRINGS_data_to_string_alloc (
      &gkch->h_payto,
      sizeof (gkch->h_payto));
    GNUNET_snprintf (arg_str,
                     sizeof (arg_str),
                     "kyc-check/%s",
                     hps);
    GNUNET_free (hps);
  }
  tms = gkch->timeout.rel_value_us
        / GNUNET_TIME_UNIT_MILLISECONDS.rel_value_us;
  GNUNET_snprintf (timeout_ms,
                   sizeof (timeout_ms),
                   "%llu",
                   tms);
  GNUNET_snprintf (krg_str,
                   sizeof (krg_str),
                   "%llu",
                   (unsigned long long) gkch->known_rule_gen);
  GNUNET_snprintf (lpt_str,
                   sizeof (lpt_str),
                   "%d",
                   (int) gkch->lpt);
  gkch->url
    = TALER_url_join (
        gkch->base_url,
        arg_str,
        "timeout_ms",
        GNUNET_TIME_relative_is_zero (gkch->timeout)
        ? NULL
        : timeout_ms,
        "min_rule",
        0 == gkch->known_rule_gen
        ? NULL
        : krg_str,
        "lpt",
        TALER_EXCHANGE_KLPT_NONE == gkch->lpt
        ? NULL
        : lpt_str,
        NULL);
  if (NULL == gkch->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  eh = TALER_EXCHANGE_curl_easy_get_ (gkch->url);
  if (NULL == eh)
  {
    GNUNET_break (0);
    GNUNET_free (gkch->url);
    gkch->url = NULL;
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  if (0 != tms)
  {
    GNUNET_break (CURLE_OK ==
                  curl_easy_setopt (eh,
                                    CURLOPT_TIMEOUT_MS,
                                    (long) (tms + 500L)));
  }
  {
    union TALER_AccountPublicKeyP account_pub;
    union TALER_AccountSignatureP account_sig;
    char *sig_hdr;
    char *pub_hdr;
    char *hdr;

    GNUNET_CRYPTO_eddsa_key_get_public (
      &gkch->account_priv.reserve_priv.eddsa_priv,
      &account_pub.reserve_pub.eddsa_pub);
    TALER_account_kyc_auth_sign (&gkch->account_priv,
                                 &account_sig);

    sig_hdr = GNUNET_STRINGS_data_to_string_alloc (
      &account_sig,
      sizeof (account_sig));
    GNUNET_asprintf (&hdr,
                     "%s: %s",
                     TALER_HTTP_HEADER_ACCOUNT_OWNER_SIGNATURE,
                     sig_hdr);
    GNUNET_free (sig_hdr);
    job_headers = curl_slist_append (job_headers,
                                     hdr);
    GNUNET_free (hdr);

    pub_hdr = GNUNET_STRINGS_data_to_string_alloc (
      &account_pub,
      sizeof (account_pub));
    GNUNET_asprintf (&hdr,
                     "%s: %s",
                     TALER_HTTP_HEADER_ACCOUNT_OWNER_PUBKEY,
                     pub_hdr);
    GNUNET_free (pub_hdr);
    job_headers = curl_slist_append (job_headers,
                                     hdr);
    GNUNET_free (hdr);
    if (NULL == job_headers)
    {
      GNUNET_break (0);
      curl_easy_cleanup (eh);
      GNUNET_free (gkch->url);
      gkch->url = NULL;
      return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
    }
  }
  gkch->job
    = GNUNET_CURL_job_add2 (gkch->ctx,
                            eh,
                            job_headers,
                            &handle_kyc_check_finished,
                            gkch);
  curl_slist_free_all (job_headers);
  if (NULL == gkch->job)
  {
    GNUNET_free (gkch->url);
    gkch->url = NULL;
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  return TALER_EC_NONE;
}


void
TALER_EXCHANGE_get_kyc_check_cancel (
  struct TALER_EXCHANGE_GetKycCheckHandle *gkch)
{
  if (NULL != gkch->job)
  {
    GNUNET_CURL_job_cancel (gkch->job);
    gkch->job = NULL;
  }
  GNUNET_free (gkch->url);
  GNUNET_free (gkch->base_url);
  GNUNET_free (gkch);
}


/* end of exchange_api_get-kyc-check-H_NORMALIZED_PAYTO.c */
