/*
  This file is part of TALER
  Copyright (C) 2025 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 merchant_api_post_units.c
 * @brief Implementation of POST /private/units
 * @author Bohdan Potuzhnyi
 */
#include "platform.h"
#include <curl/curl.h>
#include <jansson.h>
#include <microhttpd.h>
#include <gnunet/gnunet_util_lib.h>
#include "taler_merchant_service.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_UnitsPostHandle
{
  /**
   * Fully qualified request URL.
   */
  char *url;

  /**
   * CURL job handle.
   */
  struct GNUNET_CURL_Job *job;

  /**
   * Callback to invoke with the result.
   */
  TALER_MERCHANT_UnitsPostCallback cb;

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

  /**
   * Execution context.
   */
  struct GNUNET_CURL_Context *ctx;

  /**
   * Helper keeping POST body and headers alive.
   */
  struct TALER_CURL_PostContext post_ctx;
};


/**
 * Called when the HTTP transfer finishes.
 *
 * @param cls operation handle
 * @param response_code HTTP status (0 on network / parsing failures)
 * @param response parsed JSON reply (NULL if unavailable)
 */
static void
handle_post_units_finished (void *cls,
                            long response_code,
                            const void *response)
{
  struct TALER_MERCHANT_UnitsPostHandle *uph = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_HttpResponse hr = {
    .http_status = (unsigned int) response_code,
    .reply = json
  };

  uph->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "POST /private/units completed with status %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  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:
    hr.ec = TALER_JSON_get_error_code (json);
    hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case 0:
    hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  default:
    TALER_MERCHANT_parse_error_details_ (json,
                                         response_code,
                                         &hr);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response %u/%d for POST /private/units\n",
                (unsigned int) response_code,
                (int) hr.ec);
    GNUNET_break_op (0);
    break;
  }
  uph->cb (uph->cb_cls,
           &hr);
  TALER_MERCHANT_units_post_cancel (uph);
}


struct TALER_MERCHANT_UnitsPostHandle *
TALER_MERCHANT_units_post (struct GNUNET_CURL_Context *ctx,
                           const char *backend_url,
                           const char *unit_id,
                           const char *unit_name_long,
                           const char *unit_name_short,
                           bool unit_allow_fraction,
                           uint32_t unit_precision_level,
                           bool unit_active,
                           const json_t *unit_name_long_i18n,
                           const json_t *unit_name_short_i18n,
                           TALER_MERCHANT_UnitsPostCallback cb,
                           void *cb_cls)
{
  struct TALER_MERCHANT_UnitsPostHandle *uph;
  json_t *req_obj;

  req_obj = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_string ("unit",
                             unit_id),
    GNUNET_JSON_pack_string ("unit_name_long",
                             unit_name_long),
    GNUNET_JSON_pack_string ("unit_name_short",
                             unit_name_short),
    GNUNET_JSON_pack_bool ("unit_allow_fraction",
                           unit_allow_fraction),
    GNUNET_JSON_pack_uint64 ("unit_precision_level",
                             (uint64_t) unit_precision_level),
    GNUNET_JSON_pack_bool ("unit_active",
                           unit_active),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_object_incref ("unit_name_long_i18n",
                                      (json_t *) unit_name_long_i18n)),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_object_incref ("unit_name_short_i18n",
                                      (json_t *) unit_name_short_i18n)));
  uph = GNUNET_new (struct TALER_MERCHANT_UnitsPostHandle);
  uph->ctx = ctx;
  uph->cb = cb;
  uph->cb_cls = cb_cls;
  uph->url = TALER_url_join (backend_url,
                             "private/units",
                             NULL);
  if (NULL == uph->url)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to build /private/units URL\n");
    json_decref (req_obj);
    GNUNET_free (uph);
    return NULL;
  }
  {
    CURL *eh;

    eh = TALER_MERCHANT_curl_easy_get_ (uph->url);
    if (GNUNET_OK !=
        TALER_curl_easy_post (&uph->post_ctx,
                              eh,
                              req_obj))
    {
      GNUNET_break (0);
      curl_easy_cleanup (eh);
      json_decref (req_obj);
      GNUNET_free (uph->url);
      GNUNET_free (uph);
      return NULL;
    }
    json_decref (req_obj);
    uph->job = GNUNET_CURL_job_add2 (ctx,
                                     eh,
                                     uph->post_ctx.headers,
                                     &handle_post_units_finished,
                                     uph);
  }
  return uph;
}


void
TALER_MERCHANT_units_post_cancel (struct TALER_MERCHANT_UnitsPostHandle *uph)
{
  if (NULL != uph->job)
  {
    GNUNET_CURL_job_cancel (uph->job);
    uph->job = NULL;
  }
  TALER_curl_easy_post_finished (&uph->post_ctx);
  GNUNET_free (uph->url);
  GNUNET_free (uph);
}


/* end of merchant_api_post_units.c */
