/*
  This file is part of TALER
  Copyright (C) 2022-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-templates-TEMPLATE_ID.c
 * @brief Implementation of the POST /templates/$TEMPLATE_ID 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-templates-TEMPLATE_ID.h>
#include "merchant_api_curl_defaults.h"
#include "merchant_api_common.h"
#include <taler/taler_json_lib.h>
#include <taler/taler_curl_lib.h>


/**
 * Handle for a POST /templates/$TEMPLATE_ID operation.
 */
struct TALER_MERCHANT_PostTemplatesHandle
{
  /**
   * 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_PostTemplatesCallback cb;

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

  /**
   * Template identifier.
   */
  char *template_id;

  /**
   * Optional summary string.
   */
  const char *summary;

  /**
   * Optional amount.
   */
  const struct TALER_Amount *amount;

  /**
   * Optional detailed contract customization (JSON).
   */
  const json_t *details;
};


/**
 * Function called when we're done processing the
 * HTTP POST /templates/$TEMPLATE_ID request.
 *
 * @param cls the `struct TALER_MERCHANT_PostTemplatesHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_post_templates_finished (void *cls,
                                long response_code,
                                const void *response)
{
  struct TALER_MERCHANT_PostTemplatesHandle *pth = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_PostTemplatesResponse ptr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };
  struct TALER_ClaimTokenP token;

  pth->job = NULL;
  switch (response_code)
  {
  case 0:
    ptr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_OK:
    {
      bool no_token;
      bool no_pay_deadline;
      struct GNUNET_JSON_Specification spec[] = {
        TALER_JSON_spec_slug ("order_id",
                              &ptr.details.ok.order_id),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_fixed_auto ("token",
                                       &token),
          &no_token),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_timestamp ("pay_deadline",
                                      &ptr.details.ok.pay_deadline),
          &no_pay_deadline),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json,
                             spec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        ptr.hr.http_status = 0;
        ptr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
      if (! no_token)
        ptr.details.ok.token = &token;
      if (no_pay_deadline)
        ptr.details.ok.pay_deadline = GNUNET_TIME_UNIT_ZERO_TS;
      break;
    }
  case MHD_HTTP_BAD_REQUEST:
    ptr.hr.ec = TALER_JSON_get_error_code (json);
    ptr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_UNAUTHORIZED:
    ptr.hr.ec = TALER_JSON_get_error_code (json);
    ptr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_FORBIDDEN:
    ptr.hr.ec = TALER_JSON_get_error_code (json);
    ptr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_NOT_FOUND:
    ptr.hr.ec = TALER_JSON_get_error_code (json);
    ptr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_CONFLICT:
    ptr.hr.ec = TALER_JSON_get_error_code (json);
    ptr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    ptr.hr.ec = TALER_JSON_get_error_code (json);
    ptr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    ptr.hr.ec = TALER_JSON_get_error_code (json);
    ptr.hr.hint = TALER_JSON_get_error_hint (json);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d\n",
                (unsigned int) response_code,
                (int) ptr.hr.ec);
    GNUNET_break_op (0);
    break;
  }
  pth->cb (pth->cb_cls,
           &ptr);
  TALER_MERCHANT_post_templates_cancel (pth);
}


struct TALER_MERCHANT_PostTemplatesHandle *
TALER_MERCHANT_post_templates_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const char *template_id)
{
  struct TALER_MERCHANT_PostTemplatesHandle *pth;

  pth = GNUNET_new (struct TALER_MERCHANT_PostTemplatesHandle);
  pth->ctx = ctx;
  pth->base_url = GNUNET_strdup (url);
  pth->template_id = GNUNET_strdup (template_id);
  return pth;
}


enum GNUNET_GenericReturnValue
TALER_MERCHANT_post_templates_set_options_ (
  struct TALER_MERCHANT_PostTemplatesHandle *pth,
  unsigned int num_options,
  const struct TALER_MERCHANT_PostTemplatesOptionValue *options)
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    switch (options[i].option)
    {
    case TALER_MERCHANT_POST_TEMPLATES_OPTION_END:
      return GNUNET_OK;
    case TALER_MERCHANT_POST_TEMPLATES_OPTION_SUMMARY:
      pth->summary = options[i].details.summary;
      break;
    case TALER_MERCHANT_POST_TEMPLATES_OPTION_AMOUNT:
      pth->amount = options[i].details.amount;
      break;
    case TALER_MERCHANT_POST_TEMPLATES_OPTION_DETAILS:
      pth->details = options[i].details.details;
      break;
    default:
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_MERCHANT_post_templates_start (
  struct TALER_MERCHANT_PostTemplatesHandle *pth,
  TALER_MERCHANT_PostTemplatesCallback cb,
  TALER_MERCHANT_POST_TEMPLATES_RESULT_CLOSURE *cb_cls)
{
  json_t *req_obj;
  CURL *eh;

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

    GNUNET_asprintf (&path,
                     "templates/%s",
                     pth->template_id);
    pth->url = TALER_url_join (pth->base_url,
                               path,
                               NULL);
    GNUNET_free (path);
  }
  if (NULL == pth->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  if (NULL != pth->details)
  {
    /* If detailed contract customization is provided, send it directly. */
    req_obj = json_incref ((json_t *) pth->details);
  }
  else
  {
    /* Build fixed-order request with optional summary and amount. */
    req_obj = GNUNET_JSON_PACK (
      GNUNET_JSON_pack_string ("template_type",
                               "fixed-order"),
      GNUNET_JSON_pack_allow_null (
        GNUNET_JSON_pack_string ("summary",
                                 pth->summary)),
      GNUNET_JSON_pack_allow_null (
        TALER_JSON_pack_amount ("amount",
                                pth->amount)));
  }
  eh = TALER_MERCHANT_curl_easy_get_ (pth->url);
  if ( (NULL == eh) ||
       (GNUNET_OK !=
        TALER_curl_easy_post (&pth->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);
  pth->job = GNUNET_CURL_job_add2 (pth->ctx,
                                   eh,
                                   pth->post_ctx.headers,
                                   &handle_post_templates_finished,
                                   pth);
  if (NULL == pth->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_MERCHANT_post_templates_cancel (
  struct TALER_MERCHANT_PostTemplatesHandle *pth)
{
  if (NULL != pth->job)
  {
    GNUNET_CURL_job_cancel (pth->job);
    pth->job = NULL;
  }
  TALER_curl_easy_post_finished (&pth->post_ctx);
  GNUNET_free (pth->template_id);
  GNUNET_free (pth->url);
  GNUNET_free (pth->base_url);
  GNUNET_free (pth);
}


/* end of merchant_api_post-templates-TEMPLATE_ID-new.c */
