/*
  This file is part of TALER
  Copyright (C) 2018-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-orders-ORDER_ID.c
 * @brief Implementation of the GET /orders/$ORDER_ID request (wallet-facing)
 * @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-orders-ORDER_ID.h>
#include "merchant_api_curl_defaults.h"
#include "merchant_api_common.h"
#include <taler/taler_json_lib.h>


/**
 * Handle for a GET /orders/$ORDER_ID operation (wallet-facing).
 */
struct TALER_MERCHANT_GetOrdersHandle
{
  /**
   * 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_GetOrdersCallback cb;

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

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

  /**
   * Order ID.
   */
  char *order_id;

  /**
   * Hash of the contract terms (for authentication).
   */
  struct TALER_PrivateContractHashP h_contract;

  /**
   * Claim token for unclaimed order authentication.
   */
  struct TALER_ClaimTokenP token;

  /**
   * Session ID for repurchase detection, or NULL.
   */
  char *session_id;

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

  /**
   * Minimum refund amount to wait for, or NULL if unset.
   */
  struct TALER_Amount min_refund;

  /**
   * Whether refunded orders count for repurchase detection.
   */
  enum TALER_EXCHANGE_YesNoAll allow_refunded_for_repurchase;

  /**
   * True if @e h_contract was set.
   */
  bool have_h_contract;

  /**
   * True if @e token was set.
   */
  bool have_token;

  /**
   * True if @e min_refund was set.
   */
  bool have_min_refund;

  /**
   * If true, wait until refund is confirmed obtained.
   */
  bool await_refund_obtained;
};


/**
 * Function called when we're done processing the
 * HTTP GET /orders/$ORDER_ID request (wallet-facing).
 *
 * @param cls the `struct TALER_MERCHANT_GetOrdersHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_get_order_finished (void *cls,
                           long response_code,
                           const void *response)
{
  struct TALER_MERCHANT_GetOrdersHandle *oph = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_GetOrdersResponse owgr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  oph->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Got /orders/$ORDER_ID response with status code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case MHD_HTTP_OK:
    {
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_bool ("refunded",
                               &owgr.details.ok.refunded),
        GNUNET_JSON_spec_bool ("refund_pending",
                               &owgr.details.ok.refund_pending),
        TALER_JSON_spec_amount_any ("refund_amount",
                                    &owgr.details.ok.refund_amount),
        GNUNET_JSON_spec_mark_optional (
          TALER_JSON_spec_amount_any ("refund_taken",
                                      &owgr.details.ok.refund_taken),
          NULL),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json,
                             spec,
                             NULL, NULL))
      {
        owgr.hr.http_status = 0;
        owgr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
      oph->cb (oph->cb_cls,
               &owgr);
      TALER_MERCHANT_get_orders_cancel (oph);
      return;
    }
  case MHD_HTTP_ACCEPTED:
    {
      struct GNUNET_JSON_Specification spec[] = {
        TALER_JSON_spec_web_url (
          "public_reorder_url",
          &owgr.details.accepted.public_reorder_url),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json,
                             spec,
                             NULL, NULL))
      {
        owgr.hr.http_status = 0;
        owgr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
      oph->cb (oph->cb_cls,
               &owgr);
      TALER_MERCHANT_get_orders_cancel (oph);
      return;
    }
  case MHD_HTTP_FOUND:
    /* Redirect; Location header has the target URL.
       No JSON body expected. */
    break;
  case MHD_HTTP_PAYMENT_REQUIRED:
    {
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_string (
          "taler_pay_uri",
          &owgr.details.payment_required.taler_pay_uri),
        GNUNET_JSON_spec_mark_optional (
          TALER_JSON_spec_slug (
            "already_paid_order_id",
            &owgr.details.payment_required.already_paid_order_id),
          NULL),
        GNUNET_JSON_spec_mark_optional (
          TALER_JSON_spec_web_url (
            "fulfillment_url",
            &owgr.details.payment_required.fulfillment_url),
          NULL),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json,
                             spec,
                             NULL, NULL))
      {
        owgr.hr.http_status = 0;
        owgr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
      oph->cb (oph->cb_cls,
               &owgr);
      TALER_MERCHANT_get_orders_cancel (oph);
      return;
    }
  case MHD_HTTP_BAD_REQUEST:
    owgr.hr.ec = TALER_JSON_get_error_code (json);
    owgr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_FORBIDDEN:
    owgr.hr.ec = TALER_JSON_get_error_code (json);
    owgr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_NOT_FOUND:
    owgr.hr.ec = TALER_JSON_get_error_code (json);
    owgr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_NOT_ACCEPTABLE:
    owgr.hr.ec = TALER_JSON_get_error_code (json);
    owgr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_CONFLICT:
    owgr.hr.ec = TALER_JSON_get_error_code (json);
    owgr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    owgr.hr.ec = TALER_JSON_get_error_code (json);
    owgr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    TALER_MERCHANT_parse_error_details_ (json,
                                         response_code,
                                         &owgr.hr);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d\n",
                (unsigned int) response_code,
                (int) owgr.hr.ec);
    break;
  }
  oph->cb (oph->cb_cls,
           &owgr);
  TALER_MERCHANT_get_orders_cancel (oph);
}


struct TALER_MERCHANT_GetOrdersHandle *
TALER_MERCHANT_get_orders_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const char *order_id)
{
  struct TALER_MERCHANT_GetOrdersHandle *oph;

  oph = GNUNET_new (struct TALER_MERCHANT_GetOrdersHandle);
  oph->ctx = ctx;
  oph->base_url = GNUNET_strdup (url);
  oph->order_id = GNUNET_strdup (order_id);
  oph->allow_refunded_for_repurchase = TALER_EXCHANGE_YNA_NO;
  return oph;
}


enum GNUNET_GenericReturnValue
TALER_MERCHANT_get_orders_set_options_ (
  struct TALER_MERCHANT_GetOrdersHandle *oph,
  unsigned int num_options,
  const struct TALER_MERCHANT_GetOrdersOptionValue *options)
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    const struct TALER_MERCHANT_GetOrdersOptionValue *opt =
      &options[i];

    switch (opt->option)
    {
    case TALER_MERCHANT_GET_ORDERS_OPTION_END:
      return GNUNET_OK;
    case TALER_MERCHANT_GET_ORDERS_OPTION_TIMEOUT:
      oph->timeout = opt->details.timeout;
      break;
    case TALER_MERCHANT_GET_ORDERS_OPTION_SESSION_ID:
      GNUNET_free (oph->session_id);
      if (NULL != opt->details.session_id)
        oph->session_id = GNUNET_strdup (opt->details.session_id);
      break;
    case TALER_MERCHANT_GET_ORDERS_OPTION_MIN_REFUND:
      oph->min_refund = opt->details.min_refund;
      oph->have_min_refund = true;
      break;
    case TALER_MERCHANT_GET_ORDERS_OPTION_AWAIT_REFUND_OBTAINED:
      oph->await_refund_obtained = opt->details.await_refund_obtained;
      break;
    case TALER_MERCHANT_GET_ORDERS_OPTION_H_CONTRACT:
      oph->h_contract = opt->details.h_contract;
      oph->have_h_contract = true;
      break;
    case TALER_MERCHANT_GET_ORDERS_OPTION_TOKEN:
      oph->token = opt->details.token;
      oph->have_token = true;
      break;
    case TALER_MERCHANT_GET_ORDERS_OPTION_ALLOW_REFUNDED_FOR_REPURCHASE:
      oph->allow_refunded_for_repurchase
        = opt->details.allow_refunded_for_repurchase;
      break;
    default:
      GNUNET_break (0);
      return GNUNET_NO;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_MERCHANT_get_orders_start (
  struct TALER_MERCHANT_GetOrdersHandle *oph,
  TALER_MERCHANT_GetOrdersCallback cb,
  TALER_MERCHANT_GET_ORDERS_RESULT_CLOSURE *cb_cls)
{
  CURL *eh;
  unsigned int tms;

  oph->cb = cb;
  oph->cb_cls = cb_cls;
  tms = (unsigned int) (oph->timeout.rel_value_us
                        / GNUNET_TIME_UNIT_MILLISECONDS.rel_value_us);
  {
    struct GNUNET_CRYPTO_HashAsciiEncoded h_contract_s;
    char *token_s = NULL;
    char *path;
    char timeout_ms[32];
    const char *yna_s;

    if (oph->have_h_contract)
      GNUNET_CRYPTO_hash_to_enc (&oph->h_contract.hash,
                                 &h_contract_s);
    if (oph->have_token)
      token_s = GNUNET_STRINGS_data_to_string_alloc (
        &oph->token,
        sizeof (oph->token));
    GNUNET_snprintf (timeout_ms,
                     sizeof (timeout_ms),
                     "%u",
                     tms);
    GNUNET_asprintf (&path,
                     "orders/%s",
                     oph->order_id);
    yna_s = (TALER_EXCHANGE_YNA_NO != oph->allow_refunded_for_repurchase)
            ? TALER_yna_to_string (oph->allow_refunded_for_repurchase)
            : NULL;
    oph->url = TALER_url_join (oph->base_url,
                               path,
                               "h_contract",
                               oph->have_h_contract
                               ? h_contract_s.encoding
                               : NULL,
                               "token",
                               token_s,
                               "session_id",
                               oph->session_id,
                               "timeout_ms",
                               (0 != tms)
                               ? timeout_ms
                               : NULL,
                               "refund",
                               oph->have_min_refund
                               ? TALER_amount2s (&oph->min_refund)
                               : NULL,
                               "await_refund_obtained",
                               oph->await_refund_obtained
                               ? "yes"
                               : NULL,
                               "allow_refunded_for_repurchase",
                               yna_s,
                               NULL);
    GNUNET_free (path);
    GNUNET_free (token_s);
  }
  if (NULL == oph->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  eh = TALER_MERCHANT_curl_easy_get_ (oph->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)));
  }
  oph->job = GNUNET_CURL_job_add (oph->ctx,
                                  eh,
                                  &handle_get_order_finished,
                                  oph);
  if (NULL == oph->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_MERCHANT_get_orders_cancel (
  struct TALER_MERCHANT_GetOrdersHandle *oph)
{
  if (NULL != oph->job)
  {
    GNUNET_CURL_job_cancel (oph->job);
    oph->job = NULL;
  }
  GNUNET_free (oph->url);
  GNUNET_free (oph->order_id);
  GNUNET_free (oph->session_id);
  GNUNET_free (oph->base_url);
  GNUNET_free (oph);
}


/* end of merchant_api_get-orders-ORDER_ID-new.c */
