/*
  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_get_unit.c
 * @brief Implementation of GET /private/units/$ID
 * @author Bohdan Potuzhnyi
 */
#include "platform.h"
#include <curl/curl.h>
#include <jansson.h>
#include <microhttpd.h>
#include <gnunet/gnunet_util_lib.h>
#include <gnunet/gnunet_curl_lib.h>
#include "taler_merchant_service.h"
#include "merchant_api_curl_defaults.h"
#include <taler/taler_json_lib.h>


/**
 * Handle for a GET /private/units/$ID operation.
 */
struct TALER_MERCHANT_UnitGetHandle
{
  /**
   * Fully qualified request URL.
   */
  char *url;

  /**
   * In-flight job handle.
   */
  struct GNUNET_CURL_Job *job;

  /**
   * Callback to invoke with the response.
   */
  TALER_MERCHANT_UnitGetCallback cb;

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

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


/**
 * Parse the JSON response into @a ugr.
 *
 * @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_UnitGetResponse *ugr)
{
  struct TALER_MERCHANT_UnitEntry *entry = &ugr->details.ok.unit;
  const char *unit;
  const char *unit_name_long;
  const char *unit_name_short;
  const json_t *unit_name_long_i18n = NULL;
  const json_t *unit_name_short_i18n = NULL;
  bool unit_allow_fraction;
  bool unit_active;
  bool unit_builtin;
  uint32_t unit_precision_level;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_string ("unit",
                             &unit),
    GNUNET_JSON_spec_string ("unit_name_long",
                             &unit_name_long),
    GNUNET_JSON_spec_string ("unit_name_short",
                             &unit_name_short),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_object_const ("unit_name_long_i18n",
                                     &unit_name_long_i18n),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_object_const ("unit_name_short_i18n",
                                     &unit_name_short_i18n),
      NULL),
    GNUNET_JSON_spec_bool ("unit_allow_fraction",
                           &unit_allow_fraction),
    GNUNET_JSON_spec_uint32 ("unit_precision_level",
                             &unit_precision_level),
    GNUNET_JSON_spec_bool ("unit_active",
                           &unit_active),
    GNUNET_JSON_spec_bool ("unit_builtin",
                           &unit_builtin),
    GNUNET_JSON_spec_end ()
  };

  if (GNUNET_OK !=
      GNUNET_JSON_parse (json,
                         spec,
                         NULL,
                         NULL))
  {
    GNUNET_break_op (0);
    GNUNET_JSON_parse_free (spec);
    return GNUNET_SYSERR;
  }
  GNUNET_JSON_parse_free (spec);
  entry->unit = unit;
  entry->unit_name_long = unit_name_long;
  entry->unit_name_short = unit_name_short;
  entry->unit_name_long_i18n = unit_name_long_i18n;
  entry->unit_name_short_i18n = unit_name_short_i18n;
  entry->unit_allow_fraction = unit_allow_fraction;
  entry->unit_precision_level = unit_precision_level;
  entry->unit_active = unit_active;
  entry->unit_builtin = unit_builtin;
  return GNUNET_OK;
}


/**
 * Called once the HTTP request completes.
 *
 * @param cls operation handle
 * @param response_code HTTP status (0 on client-side errors)
 * @param response parsed JSON reply (NULL if parsing failed)
 */
static void
handle_get_unit_finished (void *cls,
                          long response_code,
                          const void *response)
{
  struct TALER_MERCHANT_UnitGetHandle *ugh = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_UnitGetResponse ugr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  ugh->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "GET /private/units/$ID finished with status %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;
    }
    ugh->cb (ugh->cb_cls,
             &ugr);
    TALER_MERCHANT_unit_get_cancel (ugh);
    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;
  case 0:
    ugr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    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_WARNING,
                "Unexpected response %u/%d for GET /private/units/$ID\n",
                (unsigned int) response_code,
                (int) ugr.hr.ec);
    break;
  }
  ugh->cb (ugh->cb_cls,
           &ugr);
  TALER_MERCHANT_unit_get_cancel (ugh);
}


struct TALER_MERCHANT_UnitGetHandle *
TALER_MERCHANT_unit_get (struct GNUNET_CURL_Context *ctx,
                         const char *backend_url,
                         const char *unit_id,
                         TALER_MERCHANT_UnitGetCallback cb,
                         void *cb_cls)
{
  struct TALER_MERCHANT_UnitGetHandle *ugh;
  CURL *eh;
  char *path;

  GNUNET_asprintf (&path,
                   "private/units/%s",
                   unit_id);
  ugh = GNUNET_new (struct TALER_MERCHANT_UnitGetHandle);
  ugh->ctx = ctx;
  ugh->cb = cb;
  ugh->cb_cls = cb_cls;
  ugh->url = TALER_url_join (backend_url,
                             path,
                             NULL);
  GNUNET_free (path);
  if (NULL == ugh->url)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to build /private/units/%s URL\n",
                unit_id);
    GNUNET_free (ugh);
    return NULL;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Requesting URL '%s'\n",
              ugh->url);
  eh = TALER_MERCHANT_curl_easy_get_ (ugh->url);
  ugh->job = GNUNET_CURL_job_add (ctx,
                                  eh,
                                  &handle_get_unit_finished,
                                  ugh);
  return ugh;
}


void
TALER_MERCHANT_unit_get_cancel (struct TALER_MERCHANT_UnitGetHandle *ugh)
{
  if (NULL != ugh->job)
    GNUNET_CURL_job_cancel (ugh->job);
  GNUNET_free (ugh->url);
  GNUNET_free (ugh);
}


/* end of merchant_api_get_unit.c */
