/*
  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_get-private-units-UNIT.c
 * @brief Implementation of the GET /private/units/$UNIT 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/get-private-units-UNIT.h>
#include "merchant_api_curl_defaults.h"
#include <taler/taler_json_lib.h>


/**
 * Handle for a GET /private/units/$UNIT operation.
 */
struct TALER_MERCHANT_GetPrivateUnitHandle
{
  /**
   * 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_GetPrivateUnitCallback cb;

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

  /**
   * Reference to the execution context.
   */
  struct GNUNET_CURL_Context *ctx;

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


/**
 * Parse the JSON response into the unit entry.
 *
 * @param json full JSON reply
 * @param ugr response descriptor to populate
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_unit (const json_t *json,
            struct TALER_MERCHANT_GetPrivateUnitResponse *ugr)
{
  struct TALER_MERCHANT_UnitEntry *entry = &ugr->details.ok.unit;
  struct GNUNET_JSON_Specification spec[] = {
    TALER_JSON_spec_slug ("unit",
                          &entry->unit),
    GNUNET_JSON_spec_string ("unit_name_long",
                             &entry->unit_name_long),
    GNUNET_JSON_spec_string ("unit_name_short",
                             &entry->unit_name_short),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_object_const ("unit_name_long_i18n",
                                     &entry->unit_name_long_i18n),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_object_const ("unit_name_short_i18n",
                                     &entry->unit_name_short_i18n),
      NULL),
    GNUNET_JSON_spec_bool ("unit_allow_fraction",
                           &entry->unit_allow_fraction),
    GNUNET_JSON_spec_uint32 ("unit_precision_level",
                             &entry->unit_precision_level),
    GNUNET_JSON_spec_bool ("unit_active",
                           &entry->unit_active),
    GNUNET_JSON_spec_bool ("unit_builtin",
                           &entry->unit_builtin),
    GNUNET_JSON_spec_uint64 ("unit_serial",
                             &entry->unit_serial),
    GNUNET_JSON_spec_end ()
  };

  memset (entry,
          0,
          sizeof (*entry));
  if (GNUNET_OK !=
      GNUNET_JSON_parse (json,
                         spec,
                         NULL,
                         NULL))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Function called when we're done processing the
 * HTTP GET /private/units/$UNIT request.
 *
 * @param cls the `struct TALER_MERCHANT_GetPrivateUnitHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_get_unit_finished (void *cls,
                          long response_code,
                          const void *response)
{
  struct TALER_MERCHANT_GetPrivateUnitHandle *gpu = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_GetPrivateUnitResponse ugr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  gpu->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Got /private/units/$UNIT response with status code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case MHD_HTTP_OK:
    if (GNUNET_OK !=
        parse_unit (json,
                    &ugr))
    {
      ugr.hr.http_status = 0;
      ugr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
      break;
    }
    gpu->cb (gpu->cb_cls,
             &ugr);
    TALER_MERCHANT_get_private_unit_cancel (gpu);
    return;
  case MHD_HTTP_UNAUTHORIZED:
  case MHD_HTTP_FORBIDDEN:
  case MHD_HTTP_NOT_FOUND:
    ugr.hr.ec = TALER_JSON_get_error_code (json);
    ugr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    ugr.hr.ec = TALER_JSON_get_error_code (json);
    ugr.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) ugr.hr.ec);
    break;
  }
  gpu->cb (gpu->cb_cls,
           &ugr);
  TALER_MERCHANT_get_private_unit_cancel (gpu);
}


struct TALER_MERCHANT_GetPrivateUnitHandle *
TALER_MERCHANT_get_private_unit_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const char *unit_id)
{
  struct TALER_MERCHANT_GetPrivateUnitHandle *gpu;

  gpu = GNUNET_new (struct TALER_MERCHANT_GetPrivateUnitHandle);
  gpu->ctx = ctx;
  gpu->base_url = GNUNET_strdup (url);
  gpu->unit_id = GNUNET_strdup (unit_id);
  return gpu;
}


enum TALER_ErrorCode
TALER_MERCHANT_get_private_unit_start (
  struct TALER_MERCHANT_GetPrivateUnitHandle *gpu,
  TALER_MERCHANT_GetPrivateUnitCallback cb,
  TALER_MERCHANT_GET_PRIVATE_UNIT_RESULT_CLOSURE *cb_cls)
{
  CURL *eh;

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

    GNUNET_asprintf (&path,
                     "private/units/%s",
                     gpu->unit_id);
    gpu->url = TALER_url_join (gpu->base_url,
                               path,
                               NULL);
    GNUNET_free (path);
  }
  if (NULL == gpu->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  eh = TALER_MERCHANT_curl_easy_get_ (gpu->url);
  if (NULL == eh)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  gpu->job = GNUNET_CURL_job_add (gpu->ctx,
                                  eh,
                                  &handle_get_unit_finished,
                                  gpu);
  if (NULL == gpu->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_MERCHANT_get_private_unit_cancel (
  struct TALER_MERCHANT_GetPrivateUnitHandle *gpu)
{
  if (NULL != gpu->job)
  {
    GNUNET_CURL_job_cancel (gpu->job);
    gpu->job = NULL;
  }
  GNUNET_free (gpu->url);
  GNUNET_free (gpu->base_url);
  GNUNET_free (gpu->unit_id);
  GNUNET_free (gpu);
}


/* end of merchant_api_get-private-units-UNIT.c */
