/*
  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_units.c
 * @brief Implementation of GET /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 <gnunet/gnunet_curl_lib.h>
#include "taler_merchant_service.h"
#include "merchant_api_curl_defaults.h"
#include <taler/taler_json_lib.h>


/**
 * Maximum number of units returned in a single response.
 */
#define MAX_UNITS 1024


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

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

  /**
   * Callback to invoke with the outcome.
   */
  TALER_MERCHANT_UnitsGetCallback cb;

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

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


/**
 * Parse an individual unit entry from @a value.
 *
 * @param value JSON object describing the unit
 * @param[out] ue set to the parsed values
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_unit_entry (const json_t *value,
                  struct TALER_MERCHANT_UnitEntry *ue)
{
  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 (value,
                         spec,
                         NULL,
                         NULL))
  {
    GNUNET_break_op (0);
    GNUNET_JSON_parse_free (spec);
    return GNUNET_SYSERR;
  }
  GNUNET_JSON_parse_free (spec);
  ue->unit = unit;
  ue->unit_name_long = unit_name_long;
  ue->unit_name_short = unit_name_short;
  ue->unit_name_long_i18n = unit_name_long_i18n;
  ue->unit_name_short_i18n = unit_name_short_i18n;
  ue->unit_allow_fraction = unit_allow_fraction;
  ue->unit_precision_level = unit_precision_level;
  ue->unit_active = unit_active;
  ue->unit_builtin = unit_builtin;
  return GNUNET_OK;
}


/**
 * Parse the list of units from @a units and call the callback.
 *
 * @param json complete response JSON
 * @param units array of units
 * @param ugh ongoing operation handle
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_units (const json_t *json,
             const json_t *units,
             struct TALER_MERCHANT_UnitsGetHandle *ugh)
{
  size_t len;

  len = json_array_size (units);
  if (len > MAX_UNITS)
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }

  {
    struct TALER_MERCHANT_UnitEntry entries[GNUNET_NZL (len)];
    size_t idx;
    json_t *value;

    json_array_foreach (units, idx, value) {
      if (GNUNET_OK !=
          parse_unit_entry (value,
                            &entries[idx]))
      {
        GNUNET_break_op (0);
        return GNUNET_SYSERR;
      }
    }
    {
      struct TALER_MERCHANT_UnitsGetResponse ugr = {
        .hr.http_status = MHD_HTTP_OK,
        .hr.reply = json,
        .details = {
          .ok = {
            .units = entries,
            .units_length = (unsigned int) len
          }


        }


      };

      ugh->cb (ugh->cb_cls,
               &ugr);
    }
  }
  return GNUNET_OK;
}


/**
 * Called when the HTTP transfer finishes.
 *
 * @param cls closure, the operation handle
 * @param response_code HTTP status (0 on network errors)
 * @param response parsed JSON body (NULL if parsing failed)
 */
static void
handle_get_units_finished (void *cls,
                           long response_code,
                           const void *response)
{
  struct TALER_MERCHANT_UnitsGetHandle *ugh = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_UnitsGetResponse ugr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  ugh->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "GET /private/units finished with status %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case MHD_HTTP_OK:
    {
      const json_t *units;
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_array_const ("units",
                                      &units),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json,
                             spec,
                             NULL,
                             NULL))
      {
        GNUNET_break_op (0);
        ugr.hr.http_status = 0;
        ugr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
      if (GNUNET_OK ==
          parse_units (json,
                       units,
                       ugh))
      {
        TALER_MERCHANT_units_get_cancel (ugh);
        return;
      }
      ugr.hr.http_status = 0;
      ugr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
      break;
    }
  case MHD_HTTP_UNAUTHORIZED:
  case MHD_HTTP_FORBIDDEN:
  case MHD_HTTP_NOT_FOUND:
  case MHD_HTTP_CONFLICT:
    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 code %u/%d for GET /private/units\n",
                (unsigned int) response_code,
                (int) ugr.hr.ec);
    break;
  }
  ugh->cb (ugh->cb_cls,
           &ugr);
  TALER_MERCHANT_units_get_cancel (ugh);
}


struct TALER_MERCHANT_UnitsGetHandle *
TALER_MERCHANT_units_get (struct GNUNET_CURL_Context *ctx,
                          const char *backend_url,
                          TALER_MERCHANT_UnitsGetCallback cb,
                          void *cb_cls)
{
  struct TALER_MERCHANT_UnitsGetHandle *ugh;
  CURL *eh;

  ugh = GNUNET_new (struct TALER_MERCHANT_UnitsGetHandle);
  ugh->ctx = ctx;
  ugh->cb = cb;
  ugh->cb_cls = cb_cls;
  ugh->url = TALER_url_join (backend_url,
                             "private/units",
                             NULL);
  if (NULL == ugh->url)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to build /private/units URL\n");
    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_units_finished,
                                  ugh);
  return ugh;
}


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


/* end of merchant_api_get_units.c */
