/*
  This file is part of TALER
  Copyright (C) 2014-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_post-orders-ORDER_ID-abort.c
 * @brief Implementation of the POST /orders/$ID/abort 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/post-orders-ORDER_ID-abort.h>
#include "merchant_api_curl_defaults.h"
#include "merchant_api_common.h"
#include <taler/taler_json_lib.h>
#include <taler/taler_curl_lib.h>
#include <taler/taler_signatures.h>


/**
 * Maximum number of refunds we return.
 */
#define MAX_REFUNDS 1024


/**
 * Handle for a POST /orders/$ORDER_ID/abort operation.
 */
struct TALER_MERCHANT_PostOrdersAbortHandle
{
  /**
   * 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_PostOrdersAbortCallback cb;

  /**
   * Closure for @a cb.
   */
  TALER_MERCHANT_POST_ORDERS_ABORT_RESULT_CLOSURE *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;

  /**
   * Order identifier.
   */
  char *order_id;

  /**
   * Public key of the merchant.
   */
  struct TALER_MerchantPublicKeyP merchant_pub;

  /**
   * Hash of the contract terms.
   */
  struct TALER_PrivateContractHashP h_contract;

  /**
   * The coins we are aborting on.
   */
  struct TALER_MERCHANT_PostOrdersAbortCoin *coins;

  /**
   * Number of @e coins.
   */
  unsigned int num_coins;
};


/**
 * Check that the response for an abort is well-formed,
 * and call the application callback with the result if it is
 * OK. Otherwise returns #GNUNET_SYSERR.
 *
 * @param poah handle to operation that created the reply
 * @param[in] ar abort response, partially initialized
 * @param json the reply to parse
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
check_abort_refund (struct TALER_MERCHANT_PostOrdersAbortHandle *poah,
                    struct TALER_MERCHANT_PostOrdersAbortResponse *ar,
                    const json_t *json)
{
  const json_t *refunds;
  unsigned int num_refunds;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_array_const ("refunds",
                                  &refunds),
    GNUNET_JSON_spec_end ()
  };

  if (GNUNET_OK !=
      GNUNET_JSON_parse (json,
                         spec,
                         NULL, NULL))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  num_refunds = (unsigned int) json_array_size (refunds);
  if ( (json_array_size (refunds) != (size_t) num_refunds) ||
       (num_refunds != poah->num_coins) )
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  {
    struct TALER_MERCHANT_PostOrdersAbortedCoin res[GNUNET_NZL (num_refunds)];

    memset (res,
            0,
            sizeof (res));
    for (unsigned int i = 0; i<num_refunds; i++)
    {
      json_t *refund = json_array_get (refunds, i);
      struct TALER_MERCHANT_PostOrdersAbortedCoin *ac = &res[i];
      const char *type;
      struct GNUNET_JSON_Specification spec_type[] = {
        GNUNET_JSON_spec_string ("type",
                                 &type),
        GNUNET_JSON_spec_end ()
      };

      ac->coin_pub = poah->coins[i].coin_pub;
      if (GNUNET_OK !=
          GNUNET_JSON_parse (refund,
                             spec_type,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        return GNUNET_SYSERR;
      }
      if (0 == strcmp (type,
                       "undeposited"))
      {
        /* An "undeposited" entry (MerchantAbortPayRefundUndepositedStatus)
           carries no exchange_status and no refund confirmation to verify. */
        ac->type = TALER_MERCHANT_POAC_UNDEPOSITED;
        continue;
      }
      if (0 == strcmp (type,
                       "success"))
      {
        struct GNUNET_JSON_Specification spec_detail[] = {
          GNUNET_JSON_spec_uint32 ("exchange_status",
                                   &ac->details.success.exchange_status),
          GNUNET_JSON_spec_fixed_auto ("exchange_sig",
                                       &ac->details.success.exchange_sig),
          GNUNET_JSON_spec_fixed_auto ("exchange_pub",
                                       &ac->details.success.exchange_pub),
          GNUNET_JSON_spec_end ()
        };

        ac->type = TALER_MERCHANT_POAC_SUCCESS;
        if (GNUNET_OK !=
            GNUNET_JSON_parse (refund,
                               spec_detail,
                               NULL, NULL))
        {
          GNUNET_break_op (0);
          return GNUNET_SYSERR;
        }
        if (MHD_HTTP_OK != ac->details.success.exchange_status)
        {
          GNUNET_break_op (0);
          return GNUNET_SYSERR;
        }

        if (GNUNET_OK !=
            TALER_exchange_online_refund_confirmation_verify (
              &poah->h_contract,
              &poah->coins[i].coin_pub,
              &poah->merchant_pub,
              0,   /* transaction id */
              &poah->coins[i].amount_with_fee,
              &ac->details.success.exchange_pub,
              &ac->details.success.exchange_sig))
        {
          GNUNET_break_op (0);
          return GNUNET_SYSERR;
        }
        continue;
      }
      if (0 == strcmp (type,
                       "failure"))
      {
        struct GNUNET_JSON_Specification spec_detail[] = {
          GNUNET_JSON_spec_uint32 ("exchange_status",
                                   &ac->details.failure.exchange_status),
          TALER_JSON_spec_ec ("exchange_code",
                              &ac->details.failure.exchange_code),
          GNUNET_JSON_spec_mark_optional (
            GNUNET_JSON_spec_object_const ("exchange_reply",
                                           &ac->details.failure.exchange_reply),
            NULL),
          GNUNET_JSON_spec_end ()
        };

        ac->type = TALER_MERCHANT_POAC_FAILURE;
        if (GNUNET_OK !=
            GNUNET_JSON_parse (refund,
                               spec_detail,
                               NULL, NULL))
        {
          GNUNET_break_op (0);
          return GNUNET_SYSERR;
        }
        continue;
      }
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    switch (ar->hr.http_status)
    {
    case MHD_HTTP_OK:
      ar->details.ok.num_aborts = num_refunds;
      ar->details.ok.aborts = res;
      break;
    case MHD_HTTP_BAD_GATEWAY:
      ar->details.bad_gateway.num_aborts = num_refunds;
      ar->details.bad_gateway.aborts = res;
      break;
    default:
      GNUNET_assert (0);
    }
    poah->cb (poah->cb_cls,
              ar);
    poah->cb = NULL;
  }
  return GNUNET_OK;
}


/**
 * Function called when we're done processing the
 * HTTP POST /orders/$ID/abort request.
 *
 * @param cls the `struct TALER_MERCHANT_PostOrdersAbortHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_abort_finished (void *cls,
                       long response_code,
                       const void *response)
{
  struct TALER_MERCHANT_PostOrdersAbortHandle *poah = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_PostOrdersAbortResponse ar = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  poah->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "POST /orders/$ID/abort completed with response code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case 0:
    ar.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_OK:
    if (GNUNET_OK ==
        check_abort_refund (poah,
                            &ar,
                            json))
    {
      TALER_MERCHANT_post_orders_abort_cancel (poah);
      return;
    }
    ar.hr.http_status = 0;
    ar.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_BAD_REQUEST:
    ar.hr.ec = TALER_JSON_get_error_code (json);
    ar.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_FORBIDDEN:
    ar.hr.ec = TALER_JSON_get_error_code (json);
    ar.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_NOT_FOUND:
    ar.hr.ec = TALER_JSON_get_error_code (json);
    ar.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_REQUEST_TIMEOUT:
    ar.hr.ec = TALER_JSON_get_error_code (json);
    ar.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_PRECONDITION_FAILED:
    ar.hr.ec = TALER_JSON_get_error_code (json);
    ar.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    ar.hr.ec = TALER_JSON_get_error_code (json);
    ar.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_BAD_GATEWAY:
    if (GNUNET_OK ==
        check_abort_refund (poah,
                            &ar,
                            json))
    {
      TALER_MERCHANT_post_orders_abort_cancel (poah);
      return;
    }
    ar.hr.http_status = 0;
    ar.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_GATEWAY_TIMEOUT:
    TALER_MERCHANT_parse_error_details_ (json,
                                         response_code,
                                         &ar.hr);
    ar.details.gateway_timeout.exchange_ec = ar.hr.exchange_code;
    ar.details.gateway_timeout.exchange_http_status
      = ar.hr.exchange_http_status;
    break;
  default:
    TALER_MERCHANT_parse_error_details_ (json,
                                         response_code,
                                         &ar.hr);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d\n",
                (unsigned int) response_code,
                (int) ar.hr.ec);
    GNUNET_break_op (0);
    break;
  }
  poah->cb (poah->cb_cls,
            &ar);
  TALER_MERCHANT_post_orders_abort_cancel (poah);
}


struct TALER_MERCHANT_PostOrdersAbortHandle *
TALER_MERCHANT_post_orders_abort_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const char *order_id,
  const struct TALER_MerchantPublicKeyP *merchant_pub,
  const struct TALER_PrivateContractHashP *h_contract,
  unsigned int num_coins,
  const struct TALER_MERCHANT_PostOrdersAbortCoin coins[static num_coins])
{
  struct TALER_MERCHANT_PostOrdersAbortHandle *poah;

  if (MAX_REFUNDS < num_coins)
  {
    GNUNET_break (0);
    return NULL;
  }
  poah = GNUNET_new (struct TALER_MERCHANT_PostOrdersAbortHandle);
  poah->ctx = ctx;
  poah->base_url = GNUNET_strdup (url);
  poah->order_id = GNUNET_strdup (order_id);
  poah->merchant_pub = *merchant_pub;
  poah->h_contract = *h_contract;
  poah->num_coins = num_coins;
  poah->coins = GNUNET_new_array (num_coins,
                                  struct TALER_MERCHANT_PostOrdersAbortCoin);
  GNUNET_memcpy (
    poah->coins,
    coins,
    num_coins * sizeof (struct TALER_MERCHANT_PostOrdersAbortCoin));
  for (unsigned int i = 0; i<num_coins; i++)
    poah->coins[i].exchange_url
      = GNUNET_strdup (poah->coins[i].exchange_url);
  return poah;
}


enum TALER_ErrorCode
TALER_MERCHANT_post_orders_abort_start (
  struct TALER_MERCHANT_PostOrdersAbortHandle *poah,
  TALER_MERCHANT_PostOrdersAbortCallback cb,
  TALER_MERCHANT_POST_ORDERS_ABORT_RESULT_CLOSURE *cb_cls)
{
  json_t *abort_obj;
  json_t *j_coins;
  CURL *eh;

  poah->cb = cb;
  poah->cb_cls = cb_cls;
  {
    char *path;

    GNUNET_asprintf (&path,
                     "orders/%s/abort",
                     poah->order_id);
    poah->url = TALER_url_join (poah->base_url,
                                path,
                                NULL);
    GNUNET_free (path);
  }
  if (NULL == poah->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  j_coins = json_array ();
  if (NULL == j_coins)
  {
    GNUNET_break (0);
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  for (unsigned int i = 0; i<poah->num_coins; i++)
  {
    const struct TALER_MERCHANT_PostOrdersAbortCoin *ac = &poah->coins[i];
    json_t *j_coin;

    j_coin = GNUNET_JSON_PACK (
      GNUNET_JSON_pack_data_auto ("coin_pub",
                                  &ac->coin_pub),
      GNUNET_JSON_pack_string ("exchange_url",
                               ac->exchange_url));
    if (0 !=
        json_array_append_new (j_coins,
                               j_coin))
    {
      GNUNET_break (0);
      json_decref (j_coins);
      return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
    }
  }
  abort_obj = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_array_steal ("coins",
                                  j_coins),
    GNUNET_JSON_pack_data_auto ("h_contract",
                                &poah->h_contract));
  eh = TALER_MERCHANT_curl_easy_get_ (poah->url);
  if ( (NULL == eh) ||
       (GNUNET_OK !=
        TALER_curl_easy_post (&poah->post_ctx,
                              eh,
                              abort_obj)) )
  {
    GNUNET_break (0);
    json_decref (abort_obj);
    if (NULL != eh)
      curl_easy_cleanup (eh);
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  json_decref (abort_obj);
  poah->job = GNUNET_CURL_job_add2 (poah->ctx,
                                    eh,
                                    poah->post_ctx.headers,
                                    &handle_abort_finished,
                                    poah);
  if (NULL == poah->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_MERCHANT_post_orders_abort_cancel (
  struct TALER_MERCHANT_PostOrdersAbortHandle *poah)
{
  if (NULL != poah->job)
  {
    GNUNET_CURL_job_cancel (poah->job);
    poah->job = NULL;
  }
  TALER_curl_easy_post_finished (&poah->post_ctx);
  for (unsigned int i = 0; i < poah->num_coins; i++)
    GNUNET_free_nz ((char *) poah->coins[i].exchange_url);
  GNUNET_free (poah->coins);
  GNUNET_free (poah->order_id);
  GNUNET_free (poah->url);
  GNUNET_free (poah->base_url);
  GNUNET_free (poah);
}


/* end of merchant_api_post-orders-ORDER_ID-abort-new.c */
