/*
  This file is part of TALER
  Copyright (C) 2014-2023 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 merchant_api_post_transfers.c
 * @brief Implementation of the POST /transfers request of the merchant's HTTP API
 * @author Marcello Stanisci
 * @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 "taler_merchant_service.h"
#include "merchant_api_curl_defaults.h"
#include "merchant_api_common.h"
#include <taler/taler_curl_lib.h>
#include <taler/taler_json_lib.h>


/**
 * @brief A handle for POSTing transfer data.
 */
struct TALER_MERCHANT_PostTransfersHandle
{

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

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

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

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

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

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

};


/**
 * Function called when we're done processing the
 * HTTP POST /transfers request.
 *
 * @param cls the `struct TALER_MERCHANT_PostTransfersHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_post_transfers_finished (void *cls,
                                long response_code,
                                const void *response)
{
  struct TALER_MERCHANT_PostTransfersHandle *pth = cls;
  struct TALER_MERCHANT_PostTransfersResponse ptr = {
    .hr.reply = response,
    .hr.http_status = (unsigned int) response_code
  };

  pth->job = NULL;
  switch (response_code)
  {
  case 0:
    ptr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_NO_CONTENT:
    break;
  case MHD_HTTP_UNAUTHORIZED:
    ptr.hr.ec = TALER_JSON_get_error_code (ptr.hr.reply);
    ptr.hr.hint = TALER_JSON_get_error_hint (ptr.hr.reply);
    /* Nothing really to verify, merchant says we need to authenticate. */
    break;
  case MHD_HTTP_NOT_FOUND:
    /* Nothing really to verify, this should never
       happen, we should pass the JSON reply to the application */
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Did not find any data\n");
    ptr.hr.ec = TALER_JSON_get_error_code (ptr.hr.reply);
    ptr.hr.hint = TALER_JSON_get_error_hint (ptr.hr.reply);
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    /* Server had an internal issue; we should retry, but this API
       leaves this to the application */
    ptr.hr.ec = TALER_JSON_get_error_code (ptr.hr.reply);
    ptr.hr.hint = TALER_JSON_get_error_hint (ptr.hr.reply);
    break;
  case MHD_HTTP_BAD_GATEWAY:
    /* Exchange had an issue; we should retry, but this API
       leaves this to the application */
    ptr.hr.ec = TALER_JSON_get_error_code (ptr.hr.reply);
    ptr.hr.hint = TALER_JSON_get_error_hint (ptr.hr.reply);
    {
      uint32_t ehc;
      struct GNUNET_JSON_Specification ispec[] = {
        TALER_JSON_spec_ec ("exchange_code",
                            &ptr.details.bad_gateway.exchange_ec),
        GNUNET_JSON_spec_uint32 ("exchange_http_status",
                                 &ehc),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (ptr.hr.reply,
                             ispec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        ptr.details.bad_gateway.exchange_http_status = 0;
        ptr.details.bad_gateway.exchange_ec = TALER_EC_NONE;
        break;
      }
      else
      {
        ptr.details.bad_gateway.exchange_http_status
          = (unsigned int) ehc;
        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                    "Exchange returned %u/%u\n",
                    (unsigned int) ptr.details.bad_gateway.exchange_ec,
                    (unsigned int) ehc);
      }
    }
    break;
  case MHD_HTTP_GATEWAY_TIMEOUT:
    /* Server had an internal issue; we should retry, but this API
       leaves this to the application */
    ptr.hr.ec = TALER_JSON_get_error_code (ptr.hr.reply);
    ptr.hr.hint = TALER_JSON_get_error_hint (ptr.hr.reply);
    break;
  default:
    /* unexpected response code */
    GNUNET_break_op (0);
    TALER_MERCHANT_parse_error_details_ (ptr.hr.reply,
                                         response_code,
                                         &ptr.hr);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d\n",
                (unsigned int) ptr.hr.http_status,
                (int) ptr.hr.ec);
    break;
  }
  pth->cb (pth->cb_cls,
           &ptr);
  TALER_MERCHANT_transfers_post_cancel (pth);
}


struct TALER_MERCHANT_PostTransfersHandle *
TALER_MERCHANT_transfers_post (
  struct GNUNET_CURL_Context *ctx,
  const char *backend_url,
  const struct TALER_Amount *credit_amount,
  const struct TALER_WireTransferIdentifierRawP *wtid,
  struct TALER_FullPayto payto_uri,
  const char *exchange_url,
  TALER_MERCHANT_PostTransfersCallback cb,
  void *cb_cls)
{
  struct TALER_MERCHANT_PostTransfersHandle *pth;
  CURL *eh;
  json_t *req;

  pth = GNUNET_new (struct TALER_MERCHANT_PostTransfersHandle);
  pth->ctx = ctx;
  pth->cb = cb;
  pth->cb_cls = cb_cls;
  pth->url = TALER_url_join (backend_url,
                             "private/transfers",
                             NULL);
  if (NULL == pth->url)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Could not construct request URL.\n");
    GNUNET_free (pth);
    return NULL;
  }
  req = GNUNET_JSON_PACK (
    TALER_JSON_pack_amount ("credit_amount",
                            credit_amount),
    GNUNET_JSON_pack_data_auto ("wtid",
                                wtid),
    TALER_JSON_pack_full_payto ("payto_uri",
                                payto_uri),
    GNUNET_JSON_pack_string ("exchange_url",
                             exchange_url));
  eh = TALER_MERCHANT_curl_easy_get_ (pth->url);
  if (GNUNET_OK !=
      TALER_curl_easy_post (&pth->post_ctx,
                            eh,
                            req))
  {
    GNUNET_break (0);
    curl_easy_cleanup (eh);
    json_decref (req);
    GNUNET_free (pth->url);
    GNUNET_free (pth);
    return NULL;
  }
  json_decref (req);
  pth->job = GNUNET_CURL_job_add2 (ctx,
                                   eh,
                                   pth->post_ctx.headers,
                                   &handle_post_transfers_finished,
                                   pth);
  return pth;
}


void
TALER_MERCHANT_transfers_post_cancel (
  struct TALER_MERCHANT_PostTransfersHandle *pth)
{
  if (NULL != pth->job)
  {
    GNUNET_CURL_job_cancel (pth->job);
    pth->job = NULL;
  }
  GNUNET_free (pth->url);
  TALER_curl_easy_post_finished (&pth->post_ctx);
  GNUNET_free (pth);
}


/* end of merchant_api_post_transfers.c */
