/*
  This file is part of TALER
  Copyright (C) 2014-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-products.c
 * @brief Implementation of the GET /private/products 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-products.h>
#include "merchant_api_curl_defaults.h"
#include <taler/taler_json_lib.h>


/**
 * Maximum number of products we return.
 */
#define MAX_PRODUCTS 1024


/**
 * Handle for a GET /private/products operation.
 */
struct TALER_MERCHANT_GetPrivateProductsHandle
{
  /**
   * 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_GetPrivateProductsCallback cb;

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

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

  /**
   * Starting row for pagination.
   */
  uint64_t offset;

  /**
   * Limit on number of results.
   */
  int64_t limit;

  /**
   * Category name filter, or NULL.
   */
  char *category_filter;

  /**
   * Product name filter, or NULL.
   */
  char *name_filter;

  /**
   * Product description filter, or NULL.
   */
  char *description_filter;

  /**
   * Product group serial filter.
   */
  uint64_t product_group_serial;

  /**
   * True if offset was explicitly set.
   */
  bool have_offset;

  /**
   * True if product_group_serial was explicitly set.
   */
  bool have_product_group_serial;
};


/**
 * Parse product information from @a ia.
 *
 * @param ia JSON array (or NULL!) with product data
 * @param[in] pgr partially filled response
 * @param gpph operation handle
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_products (const json_t *ia,
                struct TALER_MERCHANT_GetPrivateProductsResponse *pgr,
                struct TALER_MERCHANT_GetPrivateProductsHandle *gpph)
{
  unsigned int ies_len = (unsigned int) json_array_size (ia);

  if ( (json_array_size (ia) != (size_t) ies_len) ||
       (ies_len > MAX_PRODUCTS) )
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  {
    struct TALER_MERCHANT_GetPrivateProductsInventoryEntry ies[
      GNUNET_NZL (ies_len)];
    size_t index;
    json_t *value;

    json_array_foreach (ia, index, value) {
      struct TALER_MERCHANT_GetPrivateProductsInventoryEntry *ie =
        &ies[index];
      struct GNUNET_JSON_Specification spec[] = {
        TALER_JSON_spec_slug ("product_id",
                              &ie->product_id),
        GNUNET_JSON_spec_uint64 ("product_serial",
                                 &ie->product_serial),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (value,
                             spec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        return GNUNET_SYSERR;
      }
    }
    pgr->details.ok.products_length = ies_len;
    pgr->details.ok.products = ies;
    gpph->cb (gpph->cb_cls,
              pgr);
    gpph->cb = NULL;
  }
  return GNUNET_OK;
}


/**
 * Function called when we're done processing the
 * HTTP GET /private/products request.
 *
 * @param cls the `struct TALER_MERCHANT_GetPrivateProductsHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_get_products_finished (void *cls,
                              long response_code,
                              const void *response)
{
  struct TALER_MERCHANT_GetPrivateProductsHandle *gpph = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_GetPrivateProductsResponse pgr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

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

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json,
                             spec,
                             NULL, NULL))
      {
        pgr.hr.http_status = 0;
        pgr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
      if (GNUNET_OK ==
          parse_products (products,
                          &pgr,
                          gpph))
      {
        TALER_MERCHANT_get_private_products_cancel (gpph);
        return;
      }
      pgr.hr.http_status = 0;
      pgr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
      break;
    }
  case MHD_HTTP_UNAUTHORIZED:
    pgr.hr.ec = TALER_JSON_get_error_code (json);
    pgr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    pgr.hr.ec = TALER_JSON_get_error_code (json);
    pgr.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) pgr.hr.ec);
    break;
  }
  gpph->cb (gpph->cb_cls,
            &pgr);
  TALER_MERCHANT_get_private_products_cancel (gpph);
}


struct TALER_MERCHANT_GetPrivateProductsHandle *
TALER_MERCHANT_get_private_products_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url)
{
  struct TALER_MERCHANT_GetPrivateProductsHandle *gpph;

  gpph = GNUNET_new (struct TALER_MERCHANT_GetPrivateProductsHandle);
  gpph->ctx = ctx;
  gpph->base_url = GNUNET_strdup (url);
  gpph->limit = 20;
  gpph->offset = INT64_MAX;
  return gpph;
}


enum GNUNET_GenericReturnValue
TALER_MERCHANT_get_private_products_set_options_ (
  struct TALER_MERCHANT_GetPrivateProductsHandle *gpph,
  unsigned int num_options,
  const struct TALER_MERCHANT_GetPrivateProductsOptionValue *options)
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    const struct TALER_MERCHANT_GetPrivateProductsOptionValue *opt =
      &options[i];

    switch (opt->option)
    {
    case TALER_MERCHANT_GET_PRIVATE_PRODUCTS_OPTION_END:
      return GNUNET_OK;
    case TALER_MERCHANT_GET_PRIVATE_PRODUCTS_OPTION_LIMIT:
      gpph->limit = opt->details.limit;
      break;
    case TALER_MERCHANT_GET_PRIVATE_PRODUCTS_OPTION_OFFSET:
      if (opt->details.offset > INT64_MAX)
      {
        GNUNET_break (0);
        return GNUNET_NO;
      }
      gpph->offset = opt->details.offset;
      gpph->have_offset = true;
      break;
    case TALER_MERCHANT_GET_PRIVATE_PRODUCTS_OPTION_CATEGORY_FILTER:
      GNUNET_free (gpph->category_filter);
      if (NULL != opt->details.category_filter)
        gpph->category_filter = GNUNET_strdup (opt->details.category_filter);
      break;
    case TALER_MERCHANT_GET_PRIVATE_PRODUCTS_OPTION_NAME_FILTER:
      GNUNET_free (gpph->name_filter);
      if (NULL != opt->details.name_filter)
        gpph->name_filter = GNUNET_strdup (opt->details.name_filter);
      break;
    case TALER_MERCHANT_GET_PRIVATE_PRODUCTS_OPTION_DESCRIPTION_FILTER:
      GNUNET_free (gpph->description_filter);
      if (NULL != opt->details.description_filter)
        gpph->description_filter =
          GNUNET_strdup (opt->details.description_filter);
      break;
    case TALER_MERCHANT_GET_PRIVATE_PRODUCTS_OPTION_PRODUCT_GROUP_SERIAL:
      gpph->product_group_serial = opt->details.product_group_serial;
      gpph->have_product_group_serial = true;
      break;
    default:
      GNUNET_break (0);
      return GNUNET_NO;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_MERCHANT_get_private_products_start (
  struct TALER_MERCHANT_GetPrivateProductsHandle *gpph,
  TALER_MERCHANT_GetPrivateProductsCallback cb,
  TALER_MERCHANT_GET_PRIVATE_PRODUCTS_RESULT_CLOSURE *cb_cls)
{
  CURL *eh;

  gpph->cb = cb;
  gpph->cb_cls = cb_cls;
  {
    char lbuf[30];
    char obuf[30];
    char pgsbuf[30];
    bool have_offset;

    GNUNET_snprintf (lbuf,
                     sizeof (lbuf),
                     "%lld",
                     (long long) gpph->limit);
    GNUNET_snprintf (obuf,
                     sizeof (obuf),
                     "%llu",
                     (unsigned long long) gpph->offset);
    if (gpph->have_product_group_serial)
      GNUNET_snprintf (pgsbuf,
                       sizeof (pgsbuf),
                       "%llu",
                       (unsigned long long) gpph->product_group_serial);
    if (gpph->limit > 0)
    {
      have_offset = gpph->have_offset
                    && (0 != gpph->offset);
    }
    else
    {
      have_offset = gpph->have_offset
                    && (INT64_MAX != gpph->offset);
    }
    gpph->url = TALER_url_join (gpph->base_url,
                                "private/products",
                                "limit",
                                (20 != gpph->limit)
                                ? lbuf
                                : NULL,
                                "offset",
                                have_offset
                                ? obuf
                                : NULL,
                                "category_filter",
                                gpph->category_filter,
                                "name_filter",
                                gpph->name_filter,
                                "description_filter",
                                gpph->description_filter,
                                "product_group_serial",
                                gpph->have_product_group_serial
                                ? pgsbuf
                                : NULL,
                                NULL);
  }
  if (NULL == gpph->url)
  {
    GNUNET_break (0);
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  }
  eh = TALER_MERCHANT_curl_easy_get_ (gpph->url);
  if (NULL == eh)
  {
    GNUNET_break (0);
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  }
  gpph->job = GNUNET_CURL_job_add (gpph->ctx,
                                   eh,
                                   &handle_get_products_finished,
                                   gpph);
  if (NULL == gpph->job)
  {
    GNUNET_break (0);
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  return TALER_EC_NONE;
}


void
TALER_MERCHANT_get_private_products_cancel (
  struct TALER_MERCHANT_GetPrivateProductsHandle *gpph)
{
  if (NULL != gpph->job)
  {
    GNUNET_CURL_job_cancel (gpph->job);
    gpph->job = NULL;
  }
  GNUNET_free (gpph->url);
  GNUNET_free (gpph->category_filter);
  GNUNET_free (gpph->name_filter);
  GNUNET_free (gpph->description_filter);
  GNUNET_free (gpph->base_url);
  GNUNET_free (gpph);
}


/* end of merchant_api_get-private-products.c */
