/*
  This file is part of TALER
  Copyright (C) 2020-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-management-instances.c
 * @brief Implementation of the POST /management/instances 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-management-instances.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 /management/instances operation.
 */
struct TALER_MERCHANT_PostManagementInstancesHandle
{
  /**
   * 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_PostManagementInstancesCallback cb;

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

  /**
   * Instance identifier.
   */
  char *instance_id;

  /**
   * Human-readable name.
   */
  char *name;

  /**
   * Address (JSON).
   */
  json_t *address;

  /**
   * Jurisdiction (JSON).
   */
  json_t *jurisdiction;

  /**
   * Whether to use the STEFAN curve.
   */
  bool use_stefan;

  /**
   * Default wire transfer delay (optional, zero if not set).
   */
  struct GNUNET_TIME_Relative default_wire_transfer_delay;

  /**
   * Default payment deadline (optional, zero if not set).
   */
  struct GNUNET_TIME_Relative default_pay_delay;

  /**
   * Default refund deadline (optional, zero if not set).
   */
  struct GNUNET_TIME_Relative default_refund_delay;

  /**
   * Default wire transfer rounding interval (optional, zero if not set).
   */
  enum GNUNET_TIME_RounderInterval default_wire_transfer_rounding_interval;

  /**
   * Authentication password (or NULL).
   */
  char *auth_password;

  /**
   * Optional email address.
   */
  char *email;

  /**
   * Optional phone number.
   */
  char *phone_number;

  /**
   * Optional website URL.
   */
  char *website;

  /**
   * Optional logo.
   */
  char *logo;

  /**
   * True if default_pay_delay was explicitly set via options.
   */
  bool have_default_pay_delay;

  /**
   * True if default_refund_delay was explicitly set via options.
   */
  bool have_default_refund_delay;

  /**
   * True if default_wire_transfer_delay was explicitly set via options.
   */
  bool have_default_wire_transfer_delay;

  /**
   * True if default_wire_transfer_rounding_interval was explicitly set via options.
   */
  bool have_default_wire_transfer_rounding_interval;
};


/**
 * Function called when we're done processing the
 * HTTP POST /management/instances request.
 *
 * @param cls the `struct TALER_MERCHANT_PostManagementInstancesHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_post_management_instances_finished (void *cls,
                                           long response_code,
                                           const void *response)
{
  struct TALER_MERCHANT_PostManagementInstancesHandle *pmih = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_PostManagementInstancesResponse mir = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  pmih->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "POST /management/instances completed with response code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case 0:
    mir.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_NO_CONTENT:
    break;
  case MHD_HTTP_ACCEPTED:
    if (GNUNET_OK !=
        TALER_MERCHANT_parse_mfa_challenge_response_ (
          json,
          &mir.details.accepted))
    {
      GNUNET_break_op (0);
      mir.hr.http_status = 0;
      mir.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    }
    break;
  case MHD_HTTP_BAD_REQUEST:
    mir.hr.ec = TALER_JSON_get_error_code (json);
    mir.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_UNAUTHORIZED:
    mir.hr.ec = TALER_JSON_get_error_code (json);
    mir.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_FORBIDDEN:
    mir.hr.ec = TALER_JSON_get_error_code (json);
    mir.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_NOT_FOUND:
    mir.hr.ec = TALER_JSON_get_error_code (json);
    mir.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_CONFLICT:
    mir.hr.ec = TALER_JSON_get_error_code (json);
    mir.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    mir.hr.ec = TALER_JSON_get_error_code (json);
    mir.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    TALER_MERCHANT_parse_error_details_ (json,
                                         response_code,
                                         &mir.hr);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d\n",
                (unsigned int) response_code,
                (int) mir.hr.ec);
    GNUNET_break_op (0);
    break;
  }
  pmih->cb (pmih->cb_cls,
            &mir);
  if (MHD_HTTP_ACCEPTED == response_code)
    TALER_MERCHANT_mfa_challenge_response_free (
      &mir.details.accepted);
  TALER_MERCHANT_post_management_instances_cancel (pmih);
}


struct TALER_MERCHANT_PostManagementInstancesHandle *
TALER_MERCHANT_post_management_instances_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const char *instance_id,
  const char *name,
  const json_t *address,
  const json_t *jurisdiction,
  bool use_stefan)
{
  struct TALER_MERCHANT_PostManagementInstancesHandle *pmih;

  pmih = GNUNET_new (struct TALER_MERCHANT_PostManagementInstancesHandle);
  pmih->ctx = ctx;
  pmih->base_url = GNUNET_strdup (url);
  pmih->instance_id = GNUNET_strdup (instance_id);
  pmih->name = GNUNET_strdup (name);
  pmih->address = json_incref ((json_t *) address);
  pmih->jurisdiction = json_incref ((json_t *) jurisdiction);
  pmih->use_stefan = use_stefan;
  return pmih;
}


enum GNUNET_GenericReturnValue
TALER_MERCHANT_post_management_instances_set_options_ (
  struct TALER_MERCHANT_PostManagementInstancesHandle *pmih,
  unsigned int num_options,
  const struct TALER_MERCHANT_PostManagementInstancesOptionValue *options)
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    switch (options[i].option)
    {
    case TALER_MERCHANT_POST_MANAGEMENT_INSTANCES_OPTION_END:
      return GNUNET_OK;
    case TALER_MERCHANT_POST_MANAGEMENT_INSTANCES_OPTION_DEFAULT_PAY_DELAY:
      pmih->default_pay_delay = options[i].details.default_pay_delay;
      pmih->have_default_pay_delay = true;
      break;
    case TALER_MERCHANT_POST_MANAGEMENT_INSTANCES_OPTION_DEFAULT_REFUND_DELAY:
      pmih->default_refund_delay = options[i].details.default_refund_delay;
      pmih->have_default_refund_delay = true;
      break;
    case
      TALER_MERCHANT_POST_MANAGEMENT_INSTANCES_OPTION_DEFAULT_WIRE_TRANSFER_DELAY
      :
      pmih->default_wire_transfer_delay
        = options[i].details.default_wire_transfer_delay;
      pmih->have_default_wire_transfer_delay = true;
      break;
    case
      TALER_MERCHANT_POST_MANAGEMENT_INSTANCES_OPTION_DEFAULT_WIRE_TRANSFER_ROUNDING_INTERVAL
      :
      pmih->default_wire_transfer_rounding_interval
        = options[i].details.default_wire_transfer_rounding_interval;
      pmih->have_default_wire_transfer_rounding_interval = true;
      break;
    case TALER_MERCHANT_POST_MANAGEMENT_INSTANCES_OPTION_EMAIL:
      GNUNET_free (pmih->email);
      if (NULL != options[i].details.email)
        pmih->email = GNUNET_strdup (options[i].details.email);
      break;
    case TALER_MERCHANT_POST_MANAGEMENT_INSTANCES_OPTION_PHONE_NUMBER:
      GNUNET_free (pmih->phone_number);
      if (NULL != options[i].details.phone_number)
        pmih->phone_number = GNUNET_strdup (options[i].details.phone_number);
      break;
    case TALER_MERCHANT_POST_MANAGEMENT_INSTANCES_OPTION_WEBSITE:
      GNUNET_free (pmih->website);
      if (NULL != options[i].details.website)
        pmih->website = GNUNET_strdup (options[i].details.website);
      break;
    case TALER_MERCHANT_POST_MANAGEMENT_INSTANCES_OPTION_LOGO:
      GNUNET_free (pmih->logo);
      if (NULL != options[i].details.logo)
        pmih->logo = GNUNET_strdup (options[i].details.logo);
      break;
    case TALER_MERCHANT_POST_MANAGEMENT_INSTANCES_OPTION_AUTH_PASSWORD:
      GNUNET_free (pmih->auth_password);
      if (NULL != options[i].details.auth_password)
        pmih->auth_password = GNUNET_strdup (
          options[i].details.auth_password);
      break;
    default:
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_MERCHANT_post_management_instances_start (
  struct TALER_MERCHANT_PostManagementInstancesHandle *pmih,
  TALER_MERCHANT_PostManagementInstancesCallback cb,
  TALER_MERCHANT_POST_MANAGEMENT_INSTANCES_RESULT_CLOSURE *cb_cls)
{
  json_t *req_obj;
  json_t *auth_obj;
  CURL *eh;

  pmih->cb = cb;
  pmih->cb_cls = cb_cls;
  pmih->url = TALER_url_join (pmih->base_url,
                              "management/instances",
                              NULL);
  if (NULL == pmih->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  if (NULL != pmih->auth_password)
  {
    auth_obj = GNUNET_JSON_PACK (
      GNUNET_JSON_pack_string ("method",
                               "token"),
      GNUNET_JSON_pack_string ("password",
                               pmih->auth_password));
  }
  else
  {
    auth_obj = GNUNET_JSON_PACK (
      GNUNET_JSON_pack_string ("method",
                               "external"));
  }
  if (NULL == auth_obj)
  {
    GNUNET_break (0);
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  req_obj = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_string ("id",
                             pmih->instance_id),
    GNUNET_JSON_pack_string ("name",
                             pmih->name),
    GNUNET_JSON_pack_object_incref ("address",
                                    pmih->address),
    GNUNET_JSON_pack_object_incref ("jurisdiction",
                                    pmih->jurisdiction),
    GNUNET_JSON_pack_bool ("use_stefan",
                           pmih->use_stefan),
    GNUNET_JSON_pack_conditional (
      pmih->have_default_wire_transfer_delay,
      GNUNET_JSON_pack_time_rel ("default_wire_transfer_delay",
                                 pmih->default_wire_transfer_delay)),
    GNUNET_JSON_pack_conditional (
      pmih->have_default_pay_delay,
      GNUNET_JSON_pack_time_rel ("default_pay_delay",
                                 pmih->default_pay_delay)),
    GNUNET_JSON_pack_conditional (
      pmih->have_default_refund_delay,
      GNUNET_JSON_pack_time_rel ("default_refund_delay",
                                 pmih->default_refund_delay)),
    GNUNET_JSON_pack_conditional (
      pmih->have_default_wire_transfer_rounding_interval,
      GNUNET_JSON_pack_time_rounder_interval (
        "default_wire_transfer_rounding_interval",
        pmih->default_wire_transfer_rounding_interval)),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_string ("email",
                               pmih->email)),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_string ("phone_number",
                               pmih->phone_number)),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_string ("website",
                               pmih->website)),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_string ("logo",
                               pmih->logo)),
    GNUNET_JSON_pack_object_steal ("auth",
                                   auth_obj));
  eh = TALER_MERCHANT_curl_easy_get_ (pmih->url);
  if ( (NULL == eh) ||
       (GNUNET_OK !=
        TALER_curl_easy_post (&pmih->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);
  pmih->job = GNUNET_CURL_job_add2 (pmih->ctx,
                                    eh,
                                    pmih->post_ctx.headers,
                                    &handle_post_management_instances_finished,
                                    pmih);
  if (NULL == pmih->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_MERCHANT_post_management_instances_cancel (
  struct TALER_MERCHANT_PostManagementInstancesHandle *pmih)
{
  if (NULL != pmih->job)
  {
    GNUNET_CURL_job_cancel (pmih->job);
    pmih->job = NULL;
  }
  TALER_curl_easy_post_finished (&pmih->post_ctx);
  json_decref (pmih->address);
  json_decref (pmih->jurisdiction);
  GNUNET_free (pmih->instance_id);
  GNUNET_free (pmih->name);
  GNUNET_free (pmih->auth_password);
  GNUNET_free (pmih->email);
  GNUNET_free (pmih->phone_number);
  GNUNET_free (pmih->website);
  GNUNET_free (pmih->logo);
  GNUNET_free (pmih->url);
  GNUNET_free (pmih->base_url);
  GNUNET_free (pmih);
}


/* end of merchant_api_post-management-instances-new.c */
