/*
  This file is part of TALER
  Copyright (C) 2023-2026 Taler Systems SA

  TALER is free software; you can redistribute it and/or modify it under the
  terms of the GNU Lesser General Public License as published by the Free Software
  Foundation; either version 2.1, 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 Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public License along with
  TALER; see the file COPYING.LGPL.  If not, see
  <http://www.gnu.org/licenses/>
*/
/**
 * @file src/lib/merchant_api_get-private-kyc.c
 * @brief Implementation of the GET /private/kyc request
 * @author Christian Grothoff
 */
#include "platform.h"
#include <curl/curl.h>
#include <jansson.h>
#include <microhttpd.h> /* just for HTTP status codes */
#include <gnunet/gnunet_util_lib.h>
#include <gnunet/gnunet_curl_lib.h>
#include <taler/merchant/get-private-kyc.h>
#include "merchant_api_curl_defaults.h"
#include <taler/taler_json_lib.h>


/**
 * Maximum length of the KYC arrays supported.
 */
#define MAX_KYC 1024


/**
 * Handle for a GET /private/kyc operation.
 */
struct TALER_MERCHANT_GetPrivateKycHandle
{
  /**
   * Base URL of the merchant backend.
   */
  char *base_url;

  /**
   * The full URL for this request.
   */
  char *url;

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

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

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

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

  /**
   * Hash of the wire account to filter by, or NULL.
   */
  const struct TALER_MerchantWireHashP *h_wire;

  /**
   * Storage for the h_wire value (if set).
   */
  struct TALER_MerchantWireHashP h_wire_val;

  /**
   * True if @e h_wire was set.
   */
  bool have_h_wire;

  /**
   * Exchange URL filter, or NULL.
   */
  char *exchange_url;

  /**
   * Long-poll target.
   */
  enum TALER_EXCHANGE_KycLongPollTarget lpt;

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

  /**
   * Instance ID for management mode, or NULL.
   */
  char *instance_id;

  /**
   * Long-poll status filter, or NULL.
   */
  char *lp_status;

  /**
   * Long-poll negated status filter, or NULL.
   */
  char *lp_not_status;

  /**
   * Long-poll ETag to suppress unchanged responses.
   */
  struct GNUNET_ShortHashCode lp_not_etag;

  /**
   * True if @e lp_not_etag was set.
   */
  bool have_lp_not_etag;
};


/**
 * Parse @a jkyc response and call the continuation on success.
 *
 * @param kyc operation handle
 * @param[in,out] kr response details
 * @param jkyc array from the reply
 * @return #GNUNET_OK on success (callback was called)
 */
static enum GNUNET_GenericReturnValue
parse_kyc (struct TALER_MERCHANT_GetPrivateKycHandle *kyc,
           struct TALER_MERCHANT_GetPrivateKycResponse *kr,
           const json_t *jkyc)
{
  unsigned int num_kycs = (unsigned int) json_array_size (jkyc);
  unsigned int num_limits = 0;
  unsigned int num_kycauths = 0;
  unsigned int pos_limits = 0;
  unsigned int pos_kycauths = 0;

  if ( (json_array_size (jkyc) != (size_t) num_kycs) ||
       (num_kycs > MAX_KYC) )
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }

  for (unsigned int i = 0; i<num_kycs; i++)
  {
    const json_t *jlimits = NULL;
    const json_t *jkycauths = NULL;
    struct GNUNET_JSON_Specification spec[] = {
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_array_const (
          "limits",
          &jlimits),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_array_const (
          "payto_kycauths",
          &jkycauths),
        NULL),
      GNUNET_JSON_spec_end ()
    };

    if (GNUNET_OK !=
        GNUNET_JSON_parse (json_array_get (jkyc,
                                           i),
                           spec,
                           NULL, NULL))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    num_limits += json_array_size (jlimits);
    num_kycauths += json_array_size (jkycauths);
    if ( (num_limits > MAX_KYC) ||
         (num_kycauths > MAX_KYC) )
    {
      /* Bound the stack VLAs declared below by an untrusted response. */
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
  }

  {
    struct TALER_MERCHANT_GetPrivateKycRedirectDetail kycs[
      GNUNET_NZL (num_kycs)];
    struct TALER_EXCHANGE_AccountLimit limits[
      GNUNET_NZL (num_limits)];
    struct TALER_FullPayto payto_kycauths[
      GNUNET_NZL (num_kycauths)];

    memset (kycs,
            0,
            sizeof (kycs));
    for (unsigned int i = 0; i<num_kycs; i++)
    {
      struct TALER_MERCHANT_GetPrivateKycRedirectDetail *rd
        = &kycs[i];
      const json_t *jlimits = NULL;
      const json_t *jkycauths = NULL;
      uint32_t hs;
      struct GNUNET_JSON_Specification spec[] = {
        TALER_JSON_spec_full_payto_uri (
          "payto_uri",
          &rd->payto_uri),
        TALER_JSON_spec_web_url (
          "exchange_url",
          &rd->exchange_url),
        GNUNET_JSON_spec_uint32 (
          "exchange_http_status",
          &hs),
        GNUNET_JSON_spec_bool (
          "no_keys",
          &rd->no_keys),
        GNUNET_JSON_spec_bool (
          "auth_conflict",
          &rd->auth_conflict),
        GNUNET_JSON_spec_mark_optional (
          TALER_JSON_spec_ec (
            "exchange_code",
            &rd->exchange_code),
          NULL),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_fixed_auto (
            "access_token",
            &rd->access_token),
          &rd->no_access_token),
        GNUNET_JSON_spec_fixed_auto (
          "h_wire",
          &rd->h_wire),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_string (
            "status",
            &rd->status),
          NULL),
        /* Mandatory since **v25** */
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_string (
            "exchange_currency",
            &rd->exchange_currency),
          NULL),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_array_const (
            "limits",
            &jlimits),
          NULL),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_array_const (
            "payto_kycauths",
            &jkycauths),
          NULL),
        GNUNET_JSON_spec_end ()
      };
      size_t j;
      json_t *jlimit;
      json_t *jkycauth;

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json_array_get (jkyc,
                                             i),
                             spec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        return GNUNET_SYSERR;
      }
      rd->exchange_http_status = (unsigned int) hs;
      rd->limits = &limits[pos_limits];
      rd->limits_length = json_array_size (jlimits);
      json_array_foreach (jlimits, j, jlimit)
      {
        struct TALER_EXCHANGE_AccountLimit *limit
          = &limits[pos_limits];
        struct GNUNET_JSON_Specification jspec[] = {
          TALER_JSON_spec_kycte (
            "operation_type",
            &limit->operation_type),
          GNUNET_JSON_spec_relative_time (
            "timeframe",
            &limit->timeframe),
          TALER_JSON_spec_amount_any (
            "threshold",
            &limit->threshold),
          GNUNET_JSON_spec_mark_optional (
            GNUNET_JSON_spec_bool (
              "soft_limit",
              &limit->soft_limit),
            NULL),
          GNUNET_JSON_spec_end ()
        };

        GNUNET_assert (pos_limits < num_limits);
        limit->soft_limit = false;
        if (GNUNET_OK !=
            GNUNET_JSON_parse (jlimit,
                               jspec,
                               NULL, NULL))
        {
          GNUNET_break_op (0);
          return GNUNET_SYSERR;
        }
        pos_limits++;
      }
      rd->payto_kycauths = &payto_kycauths[pos_kycauths];
      rd->pkycauth_length = json_array_size (jkycauths);
      json_array_foreach (jkycauths, j, jkycauth)
      {
        GNUNET_assert (pos_kycauths < num_kycauths);
        payto_kycauths[pos_kycauths].full_payto
          = (char *) json_string_value (jkycauth);
        if (NULL == payto_kycauths[pos_kycauths].full_payto)
        {
          GNUNET_break_op (0);
          return GNUNET_SYSERR;
        }
        pos_kycauths++;
      }
    }
    kr->details.ok.kycs = kycs;
    kr->details.ok.kycs_length = num_kycs;
    kyc->cb (kyc->cb_cls,
             kr);
    kyc->cb = NULL;
  }
  return GNUNET_OK;
}


/**
 * Function called when we're done processing the
 * HTTP GET /private/kyc request.
 *
 * @param cls the `struct TALER_MERCHANT_GetPrivateKycHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_get_kyc_finished (void *cls,
                         long response_code,
                         const void *response)
{
  struct TALER_MERCHANT_GetPrivateKycHandle *kyc = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_GetPrivateKycResponse kr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  kyc->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Got /private/kyc response with status code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case MHD_HTTP_OK:
    {
      const json_t *jkyc;
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_array_const ("kyc_data",
                                      &jkyc),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json,
                             spec,
                             NULL, NULL))
      {
        kr.hr.http_status = 0;
        kr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
      if (GNUNET_OK !=
          parse_kyc (kyc,
                     &kr,
                     jkyc))
      {
        kr.hr.http_status = 0;
        kr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
      /* parse_kyc called the continuation already */
      TALER_MERCHANT_get_private_kyc_cancel (kyc);
      return;
    }
  case MHD_HTTP_NO_CONTENT:
    break;
  case MHD_HTTP_NOT_MODIFIED:
    /* ETag matched; nothing changed. No body expected. */
    break;
  case MHD_HTTP_BAD_REQUEST:
    kr.hr.ec = TALER_JSON_get_error_code (json);
    kr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_UNAUTHORIZED:
    kr.hr.ec = TALER_JSON_get_error_code (json);
    kr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_NOT_FOUND:
    kr.hr.ec = TALER_JSON_get_error_code (json);
    kr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_NOT_ACCEPTABLE:
    kr.hr.ec = TALER_JSON_get_error_code (json);
    kr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_SERVICE_UNAVAILABLE:
    break;
  default:
    kr.hr.ec = TALER_JSON_get_error_code (json);
    kr.hr.hint = TALER_JSON_get_error_hint (json);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d\n",
                (unsigned int) response_code,
                (int) kr.hr.ec);
    break;
  }
  kyc->cb (kyc->cb_cls,
           &kr);
  TALER_MERCHANT_get_private_kyc_cancel (kyc);
}


struct TALER_MERCHANT_GetPrivateKycHandle *
TALER_MERCHANT_get_private_kyc_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url)
{
  struct TALER_MERCHANT_GetPrivateKycHandle *kyc;

  kyc = GNUNET_new (struct TALER_MERCHANT_GetPrivateKycHandle);
  kyc->ctx = ctx;
  kyc->base_url = GNUNET_strdup (url);
  kyc->lpt = TALER_EXCHANGE_KLPT_NONE;
  return kyc;
}


enum GNUNET_GenericReturnValue
TALER_MERCHANT_get_private_kyc_set_options_ (
  struct TALER_MERCHANT_GetPrivateKycHandle *kyc,
  unsigned int num_options,
  const struct TALER_MERCHANT_GetPrivateKycOptionValue *options)
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    const struct TALER_MERCHANT_GetPrivateKycOptionValue *opt =
      &options[i];

    switch (opt->option)
    {
    case TALER_MERCHANT_GET_PRIVATE_KYC_OPTION_END:
      return GNUNET_OK;
    case TALER_MERCHANT_GET_PRIVATE_KYC_OPTION_H_WIRE:
      if (NULL != opt->details.h_wire)
      {
        kyc->h_wire_val = *opt->details.h_wire;
        kyc->h_wire = &kyc->h_wire_val;
        kyc->have_h_wire = true;
      }
      break;
    case TALER_MERCHANT_GET_PRIVATE_KYC_OPTION_EXCHANGE_URL:
      GNUNET_free (kyc->exchange_url);
      if (NULL != opt->details.exchange_url)
        kyc->exchange_url = GNUNET_strdup (opt->details.exchange_url);
      break;
    case TALER_MERCHANT_GET_PRIVATE_KYC_OPTION_LPT:
      kyc->lpt = opt->details.lpt;
      break;
    case TALER_MERCHANT_GET_PRIVATE_KYC_OPTION_TIMEOUT:
      kyc->timeout = opt->details.timeout;
      break;
    case TALER_MERCHANT_GET_PRIVATE_KYC_OPTION_INSTANCE_ID:
      GNUNET_free (kyc->instance_id);
      if (NULL != opt->details.instance_id)
        kyc->instance_id = GNUNET_strdup (opt->details.instance_id);
      break;
    case TALER_MERCHANT_GET_PRIVATE_KYC_OPTION_LP_STATUS:
      GNUNET_free (kyc->lp_status);
      if (NULL != opt->details.lp_status)
        kyc->lp_status = GNUNET_strdup (opt->details.lp_status);
      break;
    case TALER_MERCHANT_GET_PRIVATE_KYC_OPTION_LP_NOT_STATUS:
      GNUNET_free (kyc->lp_not_status);
      if (NULL != opt->details.lp_not_status)
        kyc->lp_not_status = GNUNET_strdup (opt->details.lp_not_status);
      break;
    case TALER_MERCHANT_GET_PRIVATE_KYC_OPTION_LP_NOT_ETAG:
      if (NULL != opt->details.lp_not_etag)
      {
        kyc->lp_not_etag = *opt->details.lp_not_etag;
        kyc->have_lp_not_etag = true;
      }
      break;
    default:
      GNUNET_break (0);
      return GNUNET_NO;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_MERCHANT_get_private_kyc_start (
  struct TALER_MERCHANT_GetPrivateKycHandle *kyc,
  TALER_MERCHANT_GetPrivateKycCallback cb,
  TALER_MERCHANT_GET_PRIVATE_KYC_RESULT_CLOSURE *cb_cls)
{
  CURL *eh;
  unsigned long long tms;
  char timeout_ms[32];
  char lpt_str[32];
  char *base_path;

  kyc->cb = cb;
  kyc->cb_cls = cb_cls;

  /* Build the base path depending on whether instance_id is set */
  if (NULL != kyc->instance_id)
  {
    GNUNET_asprintf (&base_path,
                     "%smanagement/instances/%s/",
                     kyc->base_url,
                     kyc->instance_id);
  }
  else
  {
    GNUNET_asprintf (&base_path,
                     "%sprivate/",
                     kyc->base_url);
  }

  GNUNET_snprintf (lpt_str,
                   sizeof (lpt_str),
                   "%d",
                   (int) kyc->lpt);
  tms = kyc->timeout.rel_value_us
        / GNUNET_TIME_UNIT_MILLISECONDS.rel_value_us;
  GNUNET_snprintf (timeout_ms,
                   sizeof (timeout_ms),
                   "%llu",
                   tms);
  {
    char etag_str[sizeof (struct GNUNET_ShortHashCode) * 2 + 1];

    if (kyc->have_lp_not_etag)
    {
      char *end;

      end = GNUNET_STRINGS_data_to_string (
        &kyc->lp_not_etag,
        sizeof (kyc->lp_not_etag),
        etag_str,
        sizeof (etag_str) - 1);
      *end = '\0';
    }
    kyc->url
      = TALER_url_join (
          base_path,
          "kyc",
          "h_wire",
          kyc->have_h_wire
          ? GNUNET_h2s_full (&kyc->h_wire_val.hash)
          : NULL,
          "exchange_url",
          kyc->exchange_url,
          "timeout_ms",
          GNUNET_TIME_relative_is_zero (kyc->timeout)
          ? NULL
          : timeout_ms,
          "lpt",
          TALER_EXCHANGE_KLPT_NONE == kyc->lpt
          ? NULL
          : lpt_str,
          "lp_status",
          kyc->lp_status,
          "lp_not_status",
          kyc->lp_not_status,
          "lp_not_etag",
          kyc->have_lp_not_etag
          ? etag_str
          : NULL,
          NULL);
  }
  GNUNET_free (base_path);
  if (NULL == kyc->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  eh = TALER_MERCHANT_curl_easy_get_ (kyc->url);
  if (NULL == eh)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  if (0 != tms)
  {
    GNUNET_break (CURLE_OK ==
                  curl_easy_setopt (eh,
                                    CURLOPT_TIMEOUT_MS,
                                    (long) (tms + 100L)));
  }
  kyc->job = GNUNET_CURL_job_add (kyc->ctx,
                                  eh,
                                  &handle_get_kyc_finished,
                                  kyc);
  if (NULL == kyc->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_MERCHANT_get_private_kyc_cancel (
  struct TALER_MERCHANT_GetPrivateKycHandle *kyc)
{
  if (NULL != kyc->job)
  {
    GNUNET_CURL_job_cancel (kyc->job);
    kyc->job = NULL;
  }
  GNUNET_free (kyc->url);
  GNUNET_free (kyc->exchange_url);
  GNUNET_free (kyc->instance_id);
  GNUNET_free (kyc->lp_status);
  GNUNET_free (kyc->lp_not_status);
  GNUNET_free (kyc->base_url);
  GNUNET_free (kyc);
}


/* end of merchant_api_get-private-kyc-new.c */
