/*
  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_statistics.c
 * @brief Implementation of the GET /statistics-[counter,amount]/$SLUG request of the merchant's HTTP API
 * @author Martin Schanzenbach
 */
#include "platform.h"
#include <curl/curl.h>
#include <gnunet/gnunet_common.h>
#include <gnunet/gnunet_json_lib.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_service.h"
#include "merchant_api_curl_defaults.h"
#include <taler/taler_json_lib.h>
#include <taler/taler_signatures.h>

/**
 * Maximum number of statistics we return
 */
#define MAX_STATISTICS 1024

/**
 * Handle for a GET /statistics-amount/$SLUG operation.
 */
struct TALER_MERCHANT_StatisticsAmountGetHandle
{
  /**
   * The url for this request.
   */
  char *url;

  /**
   * Handle for the request.
   */
  struct GNUNET_CURL_Job *job;

  /**
   * Function to call with the result.
   */
  TALER_MERCHANT_StatisticsAmountGetCallback cb;

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

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

};

/**
 * Handle for a GET /statistics-counter/$SLUG operation.
 */
struct TALER_MERCHANT_StatisticsCounterGetHandle
{
  /**
   * The url for this request.
   */
  char *url;

  /**
   * Handle for the request.
   */
  struct GNUNET_CURL_Job *job;

  /**
   * Function to call with the result.
   */
  TALER_MERCHANT_StatisticsCounterGetCallback cb;

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

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

};


/**
 * Parse interval information from buckets and intervals.
 *
 * @param json overall JSON reply
 * @param jbuckets JSON array (or NULL!) with bucket data
 * @param buckets_description human-readable description for the buckets
 * @param jintervals JSON array (or NULL!) with bucket data
 * @param intervals_description human-readable description for the intervals
 * @param sgh operation handle
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_intervals_and_buckets_amt (
  const json_t *json,
  const json_t *jbuckets,
  const char *buckets_description,
  const json_t *jintervals,
  const char *intervals_description,
  struct TALER_MERCHANT_StatisticsAmountGetHandle *sgh
  )
{
  unsigned int resp_buckets_len = json_array_size (jbuckets);
  unsigned int resp_intervals_len = json_array_size (jintervals);

  if ( (json_array_size (jbuckets) != (size_t)  resp_buckets_len) ||
       (json_array_size (jintervals) != (size_t)  resp_intervals_len) ||
       (resp_intervals_len = resp_buckets_len > MAX_STATISTICS) )
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  {
    struct TALER_MERCHANT_StatisticAmountByBucket resp_buckets[
      GNUNET_NZL (resp_buckets_len)];
    struct TALER_MERCHANT_StatisticAmountByInterval resp_intervals[
      GNUNET_NZL (resp_intervals_len)];
    size_t index;
    json_t *value;
    enum GNUNET_GenericReturnValue ret;

    ret = GNUNET_OK;
    json_array_foreach (jintervals, index, value) {
      struct TALER_MERCHANT_StatisticAmountByInterval *jinterval
        = &resp_intervals[index];
      const json_t *amounts_arr;
      size_t amounts_len;

      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_timestamp ("start_time",
                                    &jinterval->start_time),
        GNUNET_JSON_spec_array_const ("cumulative_amounts",
                                      &amounts_arr),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (value,
                             spec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        ret = GNUNET_SYSERR;
        continue;
      }
      if (GNUNET_SYSERR == ret)
        break;
      amounts_len = json_array_size (amounts_arr);
      {
        struct TALER_Amount amt_arr[amounts_len];
        size_t aindex;
        json_t *avalue;

        jinterval->cumulative_amount_len = amounts_len;
        jinterval->cumulative_amounts = amt_arr;
        json_array_foreach (amounts_arr, aindex, avalue) {
          if (! json_is_string (avalue))
          {
            GNUNET_break_op (0);
            return GNUNET_SYSERR;
          }
          if (GNUNET_OK !=
              TALER_string_to_amount (json_string_value (avalue),
                                      &amt_arr[aindex]))
          {
            GNUNET_break_op (0);
            return GNUNET_SYSERR;
          }
        }
      }
    }
    ret = GNUNET_OK;
    json_array_foreach (jbuckets, index, value) {
      struct TALER_MERCHANT_StatisticAmountByBucket *jbucket
        = &resp_buckets[index];
      const json_t *amounts_arr;
      size_t amounts_len;
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_timestamp ("start_time",
                                    &jbucket->start_time),
        GNUNET_JSON_spec_timestamp ("end_time",
                                    &jbucket->end_time),
        GNUNET_JSON_spec_string ("range",
                                 &jbucket->range),
        GNUNET_JSON_spec_array_const ("cumulative_amounts",
                                      &amounts_arr),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (value,
                             spec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        ret = GNUNET_SYSERR;
        continue;
      }
      if (GNUNET_SYSERR == ret)
        break;
      amounts_len = json_array_size (amounts_arr);
      if (0 > amounts_len)
      {
        GNUNET_break_op (0);
        ret = GNUNET_SYSERR;
        break;
      }
      {
        struct TALER_Amount amt_arr[amounts_len];
        size_t aindex;
        json_t *avalue;
        jbucket->cumulative_amount_len = amounts_len;
        jbucket->cumulative_amounts = amt_arr;
        json_array_foreach (amounts_arr, aindex, avalue) {
          if (! json_is_string (avalue))
          {
            GNUNET_break_op (0);
            return GNUNET_SYSERR;
          }
          if (GNUNET_OK !=
              TALER_string_to_amount (json_string_value (avalue),
                                      &amt_arr[aindex]))
          {
            GNUNET_break_op (0);
            return GNUNET_SYSERR;
          }
        }
      }
    }
    if (GNUNET_OK == ret)
    {
      struct TALER_MERCHANT_StatisticsAmountGetResponse gsr = {
        .hr.http_status = MHD_HTTP_OK,
        .hr.reply = json,
        .details.ok.buckets_length = resp_buckets_len,
        .details.ok.buckets = resp_buckets,
        .details.ok.buckets_description = buckets_description,
        .details.ok.intervals_length = resp_intervals_len,
        .details.ok.intervals = resp_intervals,
        .details.ok.intervals_description = intervals_description,
      };
      sgh->cb (sgh->cb_cls,
               &gsr);
      sgh->cb = NULL; /* just to be sure */
    }
    return ret;
  }
}


/**
 * Function called when we're done processing the
 * HTTP GET /statistics-amount/$SLUG request.
 *
 * @param cls the `struct TALER_MERCHANT_StatisticsAmountGetHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_get_statistics_amount_finished (void *cls,
                                       long response_code,
                                       const void *response)
{
  struct TALER_MERCHANT_StatisticsAmountGetHandle *handle = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_StatisticsAmountGetResponse res = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  handle->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Got /statistics-amount/$SLUG response with status code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case MHD_HTTP_OK:
    {
      const json_t *buckets;
      const json_t *intervals;
      const char *buckets_description = NULL;
      const char *intervals_description = NULL;
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_array_const ("buckets",
                                      &buckets),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_string ("buckets_description",
                                   &buckets_description),
          NULL),
        GNUNET_JSON_spec_array_const ("intervals",
                                      &intervals),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_string ("intervals_description",
                                   &intervals_description),
          NULL),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json,
                             spec,
                             NULL, NULL))
      {
        res.hr.http_status = 0;
        res.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
      if (GNUNET_OK ==
          parse_intervals_and_buckets_amt (json,
                                           buckets,
                                           buckets_description,
                                           intervals,
                                           intervals_description,
                                           handle))
      {
        TALER_MERCHANT_statistic_amount_get_cancel (handle);
        return;
      }
      res.hr.http_status = 0;
      res.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
      break;
    }
  case MHD_HTTP_UNAUTHORIZED:
    res.hr.ec = TALER_JSON_get_error_code (json);
    res.hr.hint = TALER_JSON_get_error_hint (json);
    /* Nothing really to verify, merchant says we need to authenticate. */
    break;
  case MHD_HTTP_NOT_FOUND:
    res.hr.ec = TALER_JSON_get_error_code (json);
    res.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    /* unexpected response code */
    res.hr.ec = TALER_JSON_get_error_code (json);
    res.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) res.hr.ec);
    break;
  }
}


/**
 * Parse interval information from @a ia.
 *
 * @param json overall JSON reply
 * @param jbuckets JSON array (or NULL!) with bucket data
 * @param buckets_description human-readable description for the buckets
 * @param jintervals JSON array (or NULL!) with bucket data
 * @param intervals_description human-readable description for the intervals
 * @param scgh operation handle
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_intervals_and_buckets (
  const json_t *json,
  const json_t *jbuckets,
  const char *buckets_description,
  const json_t *jintervals,
  const char *intervals_description,
  struct TALER_MERCHANT_StatisticsCounterGetHandle *scgh)
{
  unsigned int resp_buckets_len = json_array_size (jbuckets);
  unsigned int resp_intervals_len = json_array_size (jintervals);

  if ( (json_array_size (jbuckets) != (size_t)  resp_buckets_len) ||
       (json_array_size (jintervals) != (size_t)  resp_intervals_len) ||
       (resp_intervals_len = resp_buckets_len > MAX_STATISTICS) )
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  {
    struct TALER_MERCHANT_StatisticCounterByBucket resp_buckets[
      GNUNET_NZL (resp_buckets_len)];
    struct TALER_MERCHANT_StatisticCounterByInterval resp_intervals[
      GNUNET_NZL (resp_intervals_len)];
    size_t index;
    json_t *value;
    enum GNUNET_GenericReturnValue ret;

    ret = GNUNET_OK;
    json_array_foreach (jintervals, index, value) {
      struct TALER_MERCHANT_StatisticCounterByInterval *jinterval
        = &resp_intervals[index];
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_timestamp ("start_time",
                                    &jinterval->start_time),
        GNUNET_JSON_spec_uint64 ("cumulative_counter",
                                 &jinterval->cumulative_counter),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (value,
                             spec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        ret = GNUNET_SYSERR;
        continue;
      }
      if (GNUNET_SYSERR == ret)
        break;
    }
    ret = GNUNET_OK;
    json_array_foreach (jbuckets, index, value) {
      struct TALER_MERCHANT_StatisticCounterByBucket *jbucket = &resp_buckets[
        index];
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_timestamp ("start_time",
                                    &jbucket->start_time),
        GNUNET_JSON_spec_timestamp ("end_time",
                                    &jbucket->end_time),
        GNUNET_JSON_spec_string ("range",
                                 &jbucket->range),
        GNUNET_JSON_spec_uint64 ("cumulative_counter",
                                 &jbucket->cumulative_counter),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (value,
                             spec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        ret = GNUNET_SYSERR;
        continue;
      }
      if (GNUNET_SYSERR == ret)
        break;
    }
    if (GNUNET_OK == ret)
    {
      struct TALER_MERCHANT_StatisticsCounterGetResponse gsr = {
        .hr.http_status = MHD_HTTP_OK,
        .hr.reply = json,
        .details.ok.buckets_length = resp_buckets_len,
        .details.ok.buckets = resp_buckets,
        .details.ok.buckets_description = buckets_description,
        .details.ok.intervals_length = resp_intervals_len,
        .details.ok.intervals = resp_intervals,
        .details.ok.intervals_description = intervals_description,
      };
      scgh->cb (scgh->cb_cls,
                &gsr);
      scgh->cb = NULL; /* just to be sure */
    }
    return ret;
  }
}


/**
 * Function called when we're done processing the
 * HTTP GET /statistics-counter/$SLUG request.
 *
 * @param cls the `struct TALER_MERCHANT_StatisticsCounterGetHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_get_statistics_counter_finished (void *cls,
                                        long response_code,
                                        const void *response)
{
  struct TALER_MERCHANT_StatisticsCounterGetHandle *handle = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_StatisticsCounterGetResponse res = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  handle->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Got /statistics-counter/$SLUG response with status code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case MHD_HTTP_OK:
    {
      const json_t *buckets;
      const json_t *intervals;
      const char *buckets_description;
      const char *intervals_description;
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_array_const ("buckets",
                                      &buckets),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_string ("buckets_description",
                                   &buckets_description),
          NULL),
        GNUNET_JSON_spec_array_const ("intervals",
                                      &intervals),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_string ("intervals_description",
                                   &intervals_description),
          NULL),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json,
                             spec,
                             NULL, NULL))
      {
        res.hr.http_status = 0;
        res.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "%s\n", json_dumps (json, JSON_INDENT (1)));
      if (GNUNET_OK ==
          parse_intervals_and_buckets (json,
                                       buckets,
                                       buckets_description,
                                       intervals,
                                       intervals_description,
                                       handle))
      {
        TALER_MERCHANT_statistic_counter_get_cancel (handle);
        return;
      }
      res.hr.http_status = 0;
      res.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
      break;
    }
  case MHD_HTTP_UNAUTHORIZED:
    res.hr.ec = TALER_JSON_get_error_code (json);
    res.hr.hint = TALER_JSON_get_error_hint (json);
    /* Nothing really to verify, merchant says we need to authenticate. */
    break;
  case MHD_HTTP_NOT_FOUND:
    res.hr.ec = TALER_JSON_get_error_code (json);
    res.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    /* unexpected response code */
    res.hr.ec = TALER_JSON_get_error_code (json);
    res.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) res.hr.ec);
    break;
  }
}


struct TALER_MERCHANT_StatisticsCounterGetHandle *
TALER_MERCHANT_statistic_counter_get (
  struct GNUNET_CURL_Context *ctx,
  const char *backend_url,
  const char *slug,
  enum TALER_MERCHANT_StatisticsType stype,
  TALER_MERCHANT_StatisticsCounterGetCallback cb,
  void *cb_cls)
{
  struct TALER_MERCHANT_StatisticsCounterGetHandle *handle;
  CURL *eh;

  handle = GNUNET_new (struct TALER_MERCHANT_StatisticsCounterGetHandle);
  handle->ctx = ctx;
  handle->cb = cb;
  handle->cb_cls = cb_cls;
  {
    const char *filter = NULL;
    char *path;

    switch (stype)
    {
    case TALER_MERCHANT_STATISTICS_BY_BUCKET:
      filter = "bucket";
      break;
    case TALER_MERCHANT_STATISTICS_BY_INTERVAL:
      filter = "interval";
      break;
    case TALER_MERCHANT_STATISTICS_ALL:
      filter = NULL;
      break;
    }
    GNUNET_asprintf (&path,
                     "private/statistics-counter/%s",
                     slug);
    handle->url = TALER_url_join (backend_url,
                                  path,
                                  "by",
                                  filter,
                                  NULL);
    GNUNET_free (path);
  }
  if (NULL == handle->url)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Could not construct request URL.\n");
    GNUNET_free (handle);
    return NULL;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Requesting URL '%s'\n",
              handle->url);
  eh = TALER_MERCHANT_curl_easy_get_ (handle->url);
  handle->job = GNUNET_CURL_job_add (ctx,
                                     eh,
                                     &handle_get_statistics_counter_finished,
                                     handle);
  return handle;
}


void
TALER_MERCHANT_statistic_counter_get_cancel (
  struct TALER_MERCHANT_StatisticsCounterGetHandle *handle)
{
  if (NULL != handle->job)
    GNUNET_CURL_job_cancel (handle->job);
  GNUNET_free (handle->url);
  GNUNET_free (handle);
}


struct TALER_MERCHANT_StatisticsAmountGetHandle *
TALER_MERCHANT_statistic_amount_get (
  struct GNUNET_CURL_Context *ctx,
  const char *backend_url,
  const char *slug,
  enum TALER_MERCHANT_StatisticsType stype,
  TALER_MERCHANT_StatisticsAmountGetCallback cb,
  void *cb_cls)
{
  struct TALER_MERCHANT_StatisticsAmountGetHandle *handle;
  CURL *eh;

  handle = GNUNET_new (struct TALER_MERCHANT_StatisticsAmountGetHandle);
  handle->ctx = ctx;
  handle->cb = cb;
  handle->cb_cls = cb_cls;
  {
    const char *filter = NULL;
    char *path;

    switch (stype)
    {
    case TALER_MERCHANT_STATISTICS_BY_BUCKET:
      filter = "bucket";
      break;
    case TALER_MERCHANT_STATISTICS_BY_INTERVAL:
      filter = "interval";
      break;
    case TALER_MERCHANT_STATISTICS_ALL:
      filter = NULL;
      break;
    }
    GNUNET_asprintf (&path,
                     "private/statistics-amount/%s",
                     slug);
    handle->url = TALER_url_join (backend_url,
                                  path,
                                  "by",
                                  filter,
                                  NULL);
    GNUNET_free (path);
  }
  if (NULL == handle->url)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Could not construct request URL.\n");
    GNUNET_free (handle);
    return NULL;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Requesting URL '%s'\n",
              handle->url);
  eh = TALER_MERCHANT_curl_easy_get_ (handle->url);
  handle->job = GNUNET_CURL_job_add (ctx,
                                     eh,
                                     &handle_get_statistics_amount_finished,
                                     handle);
  return handle;
}


void
TALER_MERCHANT_statistic_amount_get_cancel (
  struct TALER_MERCHANT_StatisticsAmountGetHandle *handle)
{
  if (NULL != handle->job)
    GNUNET_CURL_job_cancel (handle->job);
  GNUNET_free (handle->url);
  GNUNET_free (handle);
}
