/*
  This file is part of TALER
  Copyright (C) 2025-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-private-units.c
 * @brief Implementation of the POST /private/units 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-private-units.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 /private/units operation.
 */
struct TALER_MERCHANT_PostPrivateUnitsHandle
{
  /**
   * 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_PostPrivateUnitsCallback cb;

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

  /**
   * Unit identifier.
   */
  char *unit_id;

  /**
   * Long human-readable name.
   */
  char *unit_name_long;

  /**
   * Short symbol for the unit.
   */
  char *unit_name_short;

  /**
   * Whether fractional quantities are allowed.
   */
  bool unit_allow_fraction;

  /**
   * Precision level for fractional quantities.
   */
  uint32_t unit_precision_level;

  /**
   * Whether the unit is active.
   */
  bool unit_active;

  /**
   * Whether @e unit_allow_fraction was explicitly set via options.
   */
  bool have_unit_allow_fraction;

  /**
   * Whether @e unit_precision_level was explicitly set via options.
   */
  bool have_unit_precision_level;

  /**
   * Whether @e unit_active was explicitly set via options.
   */
  bool have_unit_active;

  /**
   * Optional internationalized long names (JSON).
   */
  json_t *unit_name_long_i18n;

  /**
   * Optional internationalized short names (JSON).
   */
  json_t *unit_name_short_i18n;
};


/**
 * Function called when we're done processing the
 * HTTP POST /private/units request.
 *
 * @param cls the `struct TALER_MERCHANT_PostPrivateUnitsHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_post_units_finished (void *cls,
                            long response_code,
                            const void *response)
{
  struct TALER_MERCHANT_PostPrivateUnitsHandle *ppuh = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_PostPrivateUnitsResponse pur = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  ppuh->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "POST /private/units completed with response code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case 0:
    pur.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_NO_CONTENT:
    break;
  case MHD_HTTP_BAD_REQUEST:
  case MHD_HTTP_UNAUTHORIZED:
  case MHD_HTTP_FORBIDDEN:
  case MHD_HTTP_NOT_FOUND:
  case MHD_HTTP_CONFLICT:
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    pur.hr.ec = TALER_JSON_get_error_code (json);
    pur.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    TALER_MERCHANT_parse_error_details_ (json,
                                         response_code,
                                         &pur.hr);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d\n",
                (unsigned int) response_code,
                (int) pur.hr.ec);
    GNUNET_break_op (0);
    break;
  }
  ppuh->cb (ppuh->cb_cls,
            &pur);
  TALER_MERCHANT_post_private_units_cancel (ppuh);
}


struct TALER_MERCHANT_PostPrivateUnitsHandle *
TALER_MERCHANT_post_private_units_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const char *unit_id,
  const char *unit_name_long,
  const char *unit_name_short)
{
  struct TALER_MERCHANT_PostPrivateUnitsHandle *ppuh;

  ppuh = GNUNET_new (struct TALER_MERCHANT_PostPrivateUnitsHandle);
  ppuh->ctx = ctx;
  ppuh->base_url = GNUNET_strdup (url);
  ppuh->unit_id = GNUNET_strdup (unit_id);
  ppuh->unit_name_long = GNUNET_strdup (unit_name_long);
  ppuh->unit_name_short = GNUNET_strdup (unit_name_short);
  return ppuh;
}


enum GNUNET_GenericReturnValue
TALER_MERCHANT_post_private_units_set_options_ (
  struct TALER_MERCHANT_PostPrivateUnitsHandle *ppuh,
  unsigned int num_options,
  const struct TALER_MERCHANT_PostPrivateUnitsOptionValue *options)
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    switch (options[i].option)
    {
    case TALER_MERCHANT_POST_PRIVATE_UNITS_OPTION_END:
      return GNUNET_OK;
    case TALER_MERCHANT_POST_PRIVATE_UNITS_OPTION_UNIT_NAME_LONG_I18N:
      json_decref (ppuh->unit_name_long_i18n);
      ppuh->unit_name_long_i18n
        = json_incref ((json_t *) options[i].details.unit_name_long_i18n);
      break;
    case TALER_MERCHANT_POST_PRIVATE_UNITS_OPTION_UNIT_NAME_SHORT_I18N:
      json_decref (ppuh->unit_name_short_i18n);
      ppuh->unit_name_short_i18n
        = json_incref ((json_t *) options[i].details.unit_name_short_i18n);
      break;
    case TALER_MERCHANT_POST_PRIVATE_UNITS_OPTION_UNIT_ALLOW_FRACTION:
      ppuh->unit_allow_fraction = options[i].details.unit_allow_fraction;
      ppuh->have_unit_allow_fraction = true;
      break;
    case TALER_MERCHANT_POST_PRIVATE_UNITS_OPTION_UNIT_PRECISION_LEVEL:
      ppuh->unit_precision_level = options[i].details.unit_precision_level;
      ppuh->have_unit_precision_level = true;
      break;
    case TALER_MERCHANT_POST_PRIVATE_UNITS_OPTION_UNIT_ACTIVE:
      ppuh->unit_active = options[i].details.unit_active;
      ppuh->have_unit_active = true;
      break;
    default:
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_MERCHANT_post_private_units_start (
  struct TALER_MERCHANT_PostPrivateUnitsHandle *ppuh,
  TALER_MERCHANT_PostPrivateUnitsCallback cb,
  TALER_MERCHANT_POST_PRIVATE_UNITS_RESULT_CLOSURE *cb_cls)
{
  json_t *req_obj;
  CURL *eh;

  ppuh->cb = cb;
  ppuh->cb_cls = cb_cls;
  ppuh->url = TALER_url_join (ppuh->base_url,
                              "private/units",
                              NULL);
  if (NULL == ppuh->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  req_obj = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_string ("unit",
                             ppuh->unit_id),
    GNUNET_JSON_pack_string ("unit_name_long",
                             ppuh->unit_name_long),
    GNUNET_JSON_pack_string ("unit_name_short",
                             ppuh->unit_name_short),
    GNUNET_JSON_pack_bool ("unit_allow_fraction",
                           ppuh->have_unit_allow_fraction
                           ? ppuh->unit_allow_fraction
                           : false),
    GNUNET_JSON_pack_uint64 ("unit_precision_level",
                             ppuh->have_unit_precision_level
                             ? (uint64_t) ppuh->unit_precision_level
                             : 0),
    GNUNET_JSON_pack_bool ("unit_active",
                           ppuh->have_unit_active
                           ? ppuh->unit_active
                           : true),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_object_incref ("unit_name_long_i18n",
                                      ppuh->unit_name_long_i18n)),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_object_incref ("unit_name_short_i18n",
                                      ppuh->unit_name_short_i18n)));
  eh = TALER_MERCHANT_curl_easy_get_ (ppuh->url);
  if ( (NULL == eh) ||
       (GNUNET_OK !=
        TALER_curl_easy_post (&ppuh->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);
  ppuh->job = GNUNET_CURL_job_add2 (ppuh->ctx,
                                    eh,
                                    ppuh->post_ctx.headers,
                                    &handle_post_units_finished,
                                    ppuh);
  if (NULL == ppuh->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_MERCHANT_post_private_units_cancel (
  struct TALER_MERCHANT_PostPrivateUnitsHandle *ppuh)
{
  if (NULL != ppuh->job)
  {
    GNUNET_CURL_job_cancel (ppuh->job);
    ppuh->job = NULL;
  }
  TALER_curl_easy_post_finished (&ppuh->post_ctx);
  json_decref (ppuh->unit_name_long_i18n);
  json_decref (ppuh->unit_name_short_i18n);
  GNUNET_free (ppuh->unit_id);
  GNUNET_free (ppuh->unit_name_long);
  GNUNET_free (ppuh->unit_name_short);
  GNUNET_free (ppuh->url);
  GNUNET_free (ppuh->base_url);
  GNUNET_free (ppuh);
}


/* end of merchant_api_post-private-units-new.c */
