/*
  This file is part of TALER
  Copyright (C) 2015-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-wire.c
 * @brief functions to enable an exchange wire method / bank account
 * @author Christian Grothoff
 */
#include "taler/taler_json_lib.h"
#include <gnunet/gnunet_curl_lib.h>
#include <microhttpd.h>
#include "taler/exchange/post-management-wire.h"
#include "exchange_api_curl_defaults.h"
#include "taler/taler_signatures.h"
#include "taler/taler_curl_lib.h"


struct TALER_EXCHANGE_PostManagementWireHandle
{

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

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

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

  /**
   * Payto URI of the exchange's bank account.
   */
  char *payto_uri_str;

  /**
   * URL of the conversion service, or NULL.
   */
  char *conversion_url;

  /**
   * URL of the open banking gateway, or NULL.
   */
  char *open_banking_gateway;

  /**
   * URL of the prepared transfer service, or NULL.
   */
  char *prepared_transfer_url;

  /**
   * JSON encoding of debit restrictions (we hold a reference).
   */
  json_t *debit_restrictions;

  /**
   * JSON encoding of credit restrictions (we hold a reference).
   */
  json_t *credit_restrictions;

  /**
   * When was this decided?
   */
  struct GNUNET_TIME_Timestamp validity_start;

  /**
   * Signature affirming the wire addition.
   */
  struct TALER_MasterSignatureP master_sig1;

  /**
   * Signature affirming the validity of the account for clients.
   */
  struct TALER_MasterSignatureP master_sig2;

  /**
   * Label to use when showing the account to users (or NULL).
   */
  char *bank_label;

  /**
   * Priority for ordering the bank accounts.
   */
  int64_t priority;

};


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

  pmwh->job = NULL;
  switch (response_code)
  {
  case 0:
    /* no reply */
    res.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    res.hr.hint = "server offline?";
    break;
  case MHD_HTTP_NO_CONTENT:
    break;
  case MHD_HTTP_BAD_REQUEST:
    res.hr.ec = TALER_JSON_get_error_code (json);
    res.hr.hint = TALER_JSON_get_error_hint (json);
    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;
  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 enable wire\n",
                (unsigned int) response_code,
                (int) res.hr.ec);
    break;
  }
  if (NULL != pmwh->cb)
  {
    pmwh->cb (pmwh->cb_cls,
              &res);
    pmwh->cb = NULL;
  }
  TALER_EXCHANGE_post_management_wire_cancel (pmwh);
}


struct TALER_EXCHANGE_PostManagementWireHandle *
TALER_EXCHANGE_post_management_wire_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const struct TALER_FullPayto payto_uri,
  struct GNUNET_TIME_Timestamp validity_start,
  const struct TALER_MasterSignatureP *master_sig1,
  const struct TALER_MasterSignatureP *master_sig2)
{
  struct TALER_EXCHANGE_PostManagementWireHandle *pmwh;
  char *msg;

  msg = TALER_payto_validate (payto_uri);
  if (NULL != msg)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "payto URI is malformed: %s\n",
                msg);
    GNUNET_free (msg);
    return NULL;
  }
  pmwh = GNUNET_new (struct TALER_EXCHANGE_PostManagementWireHandle);
  pmwh->ctx = ctx;
  pmwh->base_url = GNUNET_strdup (url);
  pmwh->payto_uri_str = GNUNET_strdup (payto_uri.full_payto);
  pmwh->debit_restrictions = json_array ();
  GNUNET_assert (NULL != pmwh->debit_restrictions);
  pmwh->credit_restrictions = json_array ();
  GNUNET_assert (NULL != pmwh->credit_restrictions);
  pmwh->validity_start = validity_start;
  pmwh->master_sig1 = *master_sig1;
  pmwh->master_sig2 = *master_sig2;
  return pmwh;
}


enum GNUNET_GenericReturnValue
TALER_EXCHANGE_post_management_wire_set_options_ (
  struct TALER_EXCHANGE_PostManagementWireHandle *pmwh,
  unsigned int num_options,
  const struct TALER_EXCHANGE_PostManagementWireOptionValue options[])
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    const struct TALER_EXCHANGE_PostManagementWireOptionValue *opt
      = &options[i];

    switch (opt->option)
    {
    case TALER_EXCHANGE_POST_MANAGEMENT_WIRE_OPTION_END:
      return GNUNET_OK;
    case TALER_EXCHANGE_POST_MANAGEMENT_WIRE_OPTION_BANK_LABEL:
      GNUNET_free (pmwh->bank_label);
      pmwh->bank_label = (NULL != opt->details.bank_label)
        ? GNUNET_strdup (opt->details.bank_label)
        : NULL;
      break;
    case TALER_EXCHANGE_POST_MANAGEMENT_WIRE_OPTION_PRIORITY:
      pmwh->priority = opt->details.priority;
      break;
    case TALER_EXCHANGE_POST_MANAGEMENT_WIRE_OPTION_CONVERSION_URL:
      GNUNET_free (pmwh->conversion_url);
      pmwh->conversion_url = (NULL != opt->details.conversion_url)
        ? GNUNET_strdup (opt->details.conversion_url)
        : NULL;
      break;
    case TALER_EXCHANGE_POST_MANAGEMENT_WIRE_OPTION_OPEN_BANKING_GATEWAY:
      GNUNET_free (pmwh->open_banking_gateway);
      pmwh->open_banking_gateway = (NULL != opt->details.open_banking_gateway)
        ? GNUNET_strdup (opt->details.open_banking_gateway)
        : NULL;
      break;
    case TALER_EXCHANGE_POST_MANAGEMENT_WIRE_OPTION_PREPARED_TRANSFER_URL:
      GNUNET_free (pmwh->prepared_transfer_url);
      pmwh->prepared_transfer_url = (NULL != opt->details.prepared_transfer_url)
        ? GNUNET_strdup (opt->details.prepared_transfer_url)
        : NULL;
      break;
    case TALER_EXCHANGE_POST_MANAGEMENT_WIRE_OPTION_CREDIT_RESTRICTIONS:
      json_decref (pmwh->credit_restrictions);
      pmwh->credit_restrictions = (NULL != opt->details.credit_restrictions)
        ? json_incref ((json_t *) opt->details.credit_restrictions)
        : json_array ();
      break;
    case TALER_EXCHANGE_POST_MANAGEMENT_WIRE_OPTION_DEBIT_RESTRICTIONS:
      json_decref (pmwh->debit_restrictions);
      pmwh->debit_restrictions = (NULL != opt->details.debit_restrictions)
        ? json_incref ((json_t *) opt->details.debit_restrictions)
        : json_array ();
      break;
    default:
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_EXCHANGE_post_management_wire_start (
  struct TALER_EXCHANGE_PostManagementWireHandle *pmwh,
  TALER_EXCHANGE_PostManagementWireCallback cb,
  TALER_EXCHANGE_POST_MANAGEMENT_WIRE_RESULT_CLOSURE *cb_cls)
{
  CURL *eh;
  json_t *body;
  struct TALER_FullPayto payto_uri = {
    .full_payto = pmwh->payto_uri_str
  };

  pmwh->cb = cb;
  pmwh->cb_cls = cb_cls;
  pmwh->url = TALER_url_join (pmwh->base_url,
                              "management/wire",
                              NULL);
  if (NULL == pmwh->url)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Could not construct request URL.\n");
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  }
  body = GNUNET_JSON_PACK (
    TALER_JSON_pack_full_payto ("payto_uri",
                                payto_uri),
    GNUNET_JSON_pack_array_incref ("debit_restrictions",
                                   pmwh->debit_restrictions),
    GNUNET_JSON_pack_array_incref ("credit_restrictions",
                                   pmwh->credit_restrictions),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_string ("conversion_url",
                               pmwh->conversion_url)),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_string ("open_banking_gateway",
                               pmwh->open_banking_gateway)),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_string ("prepared_transfer_url",
                               pmwh->prepared_transfer_url)),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_string ("bank_label",
                               pmwh->bank_label)),
    GNUNET_JSON_pack_int64 ("priority",
                            pmwh->priority),
    GNUNET_JSON_pack_data_auto ("master_sig_add",
                                &pmwh->master_sig1),
    GNUNET_JSON_pack_data_auto ("master_sig_wire",
                                &pmwh->master_sig2),
    GNUNET_JSON_pack_timestamp ("validity_start",
                                pmwh->validity_start));
  eh = TALER_EXCHANGE_curl_easy_get_ (pmwh->url);
  if ( (NULL == eh) ||
       (GNUNET_OK !=
        TALER_curl_easy_post (&pmwh->post_ctx,
                              eh,
                              body)) )
  {
    GNUNET_break (0);
    if (NULL != eh)
      curl_easy_cleanup (eh);
    json_decref (body);
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  json_decref (body);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Requesting URL '%s'\n",
              pmwh->url);
  pmwh->job = GNUNET_CURL_job_add2 (pmwh->ctx,
                                    eh,
                                    pmwh->post_ctx.headers,
                                    &handle_wire_finished,
                                    pmwh);
  if (NULL == pmwh->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_EXCHANGE_post_management_wire_cancel (
  struct TALER_EXCHANGE_PostManagementWireHandle *pmwh)
{
  if (NULL != pmwh->job)
  {
    GNUNET_CURL_job_cancel (pmwh->job);
    pmwh->job = NULL;
  }
  TALER_curl_easy_post_finished (&pmwh->post_ctx);
  json_decref (pmwh->debit_restrictions);
  json_decref (pmwh->credit_restrictions);
  GNUNET_free (pmwh->payto_uri_str);
  GNUNET_free (pmwh->conversion_url);
  GNUNET_free (pmwh->open_banking_gateway);
  GNUNET_free (pmwh->prepared_transfer_url);
  GNUNET_free (pmwh->bank_label);
  GNUNET_free (pmwh->url);
  GNUNET_free (pmwh->base_url);
  GNUNET_free (pmwh);
}


/* end of exchange_api_post-management-wire.c */
