/*
  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-claim.c
 * @brief Implementation of the POST /orders/$ID/claim 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-claim.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>


/**
 * Handle for a POST /orders/$ORDER_ID/claim operation.
 */
struct TALER_MERCHANT_PostOrdersClaimHandle
{
  /**
   * 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_PostOrdersClaimCallback cb;

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

  /**
   * Wallet nonce for claiming.
   */
  struct GNUNET_CRYPTO_EddsaPublicKey nonce;

  /**
   * Optional claim token.
   */
  const struct TALER_ClaimTokenP *token;
};


/**
 * Function called when we're done processing the
 * HTTP POST /orders/$ID/claim request.
 *
 * @param cls the `struct TALER_MERCHANT_PostOrdersClaimHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_post_order_claim_finished (void *cls,
                                  long response_code,
                                  const void *response)
{
  struct TALER_MERCHANT_PostOrdersClaimHandle *poch = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_PostOrdersClaimResponse ocr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_object_const (
      "contract_terms",
      &ocr.details.ok.contract_terms),
    GNUNET_JSON_spec_fixed_auto (
      "sig",
      &ocr.details.ok.merchant_sig),
    GNUNET_JSON_spec_end ()
  };

  poch->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "POST /orders/$ID/claim completed with response code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case MHD_HTTP_OK:
    if (GNUNET_OK !=
        GNUNET_JSON_parse (json,
                           spec,
                           NULL, NULL))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Claiming order failed: could not parse JSON response\n");
      GNUNET_break_op (0);
      ocr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
      ocr.hr.http_status = 0;
      break;
    }

    if (GNUNET_OK !=
        TALER_JSON_contract_hash (ocr.details.ok.contract_terms,
                                  &ocr.details.ok.h_contract_terms))
    {
      GNUNET_break (0);
      ocr.hr.ec
        = TALER_EC_MERCHANT_POST_ORDERS_ID_CLAIM_CLIENT_INTERNAL_FAILURE;
      ocr.hr.http_status = 0;
      break;
    }
    break;
  case MHD_HTTP_CONFLICT:
    ocr.hr.ec = TALER_JSON_get_error_code (json);
    ocr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    ocr.hr.ec = TALER_JSON_get_error_code (json);
    ocr.hr.hint = TALER_JSON_get_error_hint (json);
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "Claim order failed with HTTP status code %u/%d\n",
                (unsigned int) response_code,
                (int) ocr.hr.ec);
    break;
  }
  poch->cb (poch->cb_cls,
            &ocr);
  TALER_MERCHANT_post_orders_claim_cancel (poch);
}


struct TALER_MERCHANT_PostOrdersClaimHandle *
TALER_MERCHANT_post_orders_claim_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const char *order_id,
  const struct GNUNET_CRYPTO_EddsaPublicKey *nonce)
{
  struct TALER_MERCHANT_PostOrdersClaimHandle *poch;

  poch = GNUNET_new (struct TALER_MERCHANT_PostOrdersClaimHandle);
  poch->ctx = ctx;
  poch->base_url = GNUNET_strdup (url);
  poch->order_id = GNUNET_strdup (order_id);
  poch->nonce = *nonce;
  return poch;
}


enum GNUNET_GenericReturnValue
TALER_MERCHANT_post_orders_claim_set_options_ (
  struct TALER_MERCHANT_PostOrdersClaimHandle *poch,
  unsigned int num_options,
  const struct TALER_MERCHANT_PostOrdersClaimOptionValue *options)
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    switch (options[i].option)
    {
    case TALER_MERCHANT_POST_ORDERS_CLAIM_OPTION_END:
      return GNUNET_OK;
    case TALER_MERCHANT_POST_ORDERS_CLAIM_OPTION_TOKEN:
      poch->token = options[i].details.token;
      break;
    default:
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_MERCHANT_post_orders_claim_start (
  struct TALER_MERCHANT_PostOrdersClaimHandle *poch,
  TALER_MERCHANT_PostOrdersClaimCallback cb,
  TALER_MERCHANT_POST_ORDERS_CLAIM_RESULT_CLOSURE *cb_cls)
{
  json_t *req_obj;
  CURL *eh;

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

    GNUNET_asprintf (&path,
                     "orders/%s/claim",
                     poch->order_id);
    poch->url = TALER_url_join (poch->base_url,
                                path,
                                NULL);
    GNUNET_free (path);
  }
  if (NULL == poch->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  req_obj = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_data_auto ("nonce",
                                &poch->nonce),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_data_auto ("token",
                                  poch->token)));
  eh = TALER_MERCHANT_curl_easy_get_ (poch->url);
  if ( (NULL == eh) ||
       (GNUNET_OK !=
        TALER_curl_easy_post (&poch->post_ctx,
                              eh,
                              req_obj)) )
  {
    GNUNET_break (0);
    json_decref (req_obj);
    if (NULL != eh)
      curl_easy_cleanup (eh);
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  json_decref (req_obj);
  poch->job = GNUNET_CURL_job_add2 (poch->ctx,
                                    eh,
                                    poch->post_ctx.headers,
                                    &handle_post_order_claim_finished,
                                    poch);
  if (NULL == poch->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_MERCHANT_post_orders_claim_cancel (
  struct TALER_MERCHANT_PostOrdersClaimHandle *poch)
{
  if (NULL != poch->job)
  {
    GNUNET_CURL_job_cancel (poch->job);
    poch->job = NULL;
  }
  TALER_curl_easy_post_finished (&poch->post_ctx);
  GNUNET_free (poch->order_id);
  GNUNET_free (poch->url);
  GNUNET_free (poch->base_url);
  GNUNET_free (poch);
}


/* end of merchant_api_post-orders-ORDER_ID-claim.c */
