/*
  This file is part of TALER
  Copyright (C) 2024 Taler Systems SA

  TALER is free software; you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free Software
  Foundation; either version 3, 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 Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License along with
  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file taler-exchange-httpd_aml-statistics-get.c
 * @brief Return summary information about KYC statistics
 * @author Christian Grothoff
 */
#include "taler/platform.h"
#include <gnunet/gnunet_util_lib.h>
#include <jansson.h>
#include <microhttpd.h>
#include <pthread.h>
#include "taler/taler_json_lib.h"
#include "taler/taler_mhd_lib.h"
#include "taler/taler_signatures.h"
#include "taler-exchange-httpd.h"
#include "taler/taler_exchangedb_plugin.h"
#include "taler-exchange-httpd_aml-statistics-get.h"
#include "taler-exchange-httpd_metrics.h"

/**
 * Maximum number of statistics that can be requested in one go.
 */
#define MAX_STATS 64


/**
 * Function called with AML statistics (counters).
 *
 * @param cls JSON array to build
 * @param name name of the counter
 * @param cnt number of events for @a name in the query range
 */
static void
add_stat (
  void *cls,
  const char *name,
  uint64_t cnt)
{
  json_t *stats = cls;

  GNUNET_assert (
    0 ==
    json_array_append_new (
      stats,
      GNUNET_JSON_PACK (
        GNUNET_JSON_pack_string ("event",
                                 name),
        GNUNET_JSON_pack_uint64 ("counter",
                                 cnt))));
}


MHD_RESULT
TEH_handler_aml_kyc_statistics_get (
  struct TEH_RequestContext *rc,
  const struct TALER_AmlOfficerPublicKeyP *officer_pub,
  const char *const args[])
{
  struct GNUNET_TIME_Timestamp start_date = GNUNET_TIME_UNIT_ZERO_TS;
  struct GNUNET_TIME_Timestamp end_date = GNUNET_TIME_UNIT_FOREVER_TS;
  const char *all_names = args[0];
  json_t *stats;
  size_t max_names;

  if ( (NULL == args[0]) ||
       (NULL != args[1]) )
  {
    GNUNET_break_op (0);
    return TALER_MHD_reply_with_error (
      rc->connection,
      MHD_HTTP_NOT_FOUND,
      TALER_EC_GENERIC_ENDPOINT_UNKNOWN,
      rc->url);
  }
  TALER_MHD_parse_request_timestamp (rc->connection,
                                     "start_date",
                                     &start_date);
  TALER_MHD_parse_request_timestamp (rc->connection,
                                     "end_date",
                                     &end_date);
  if (GNUNET_TIME_absolute_is_never (end_date.abs_time))
    end_date = GNUNET_TIME_absolute_to_timestamp (
      GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_SECONDS));
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Looking for stats on %s from [%llu,%llu)\n",
              all_names,
              (unsigned long long) start_date.abs_time.abs_value_us,
              (unsigned long long) end_date.abs_time.abs_value_us);
  /* Estimate number of names in 'all_names' */
  max_names = 1;
  for (size_t i = 0; '\0' != all_names[i]; i++)
    if (' ' == all_names[i])
      max_names++;
  if (max_names > MAX_STATS)
  {
    GNUNET_break_op (0);
    return TALER_MHD_reply_with_error (
      rc->connection,
      MHD_HTTP_URI_TOO_LONG,
      TALER_EC_GENERIC_URI_TOO_LONG,
      rc->url);
  }
  stats = json_array ();
  GNUNET_assert (NULL != stats);
  {
    char *buf;
    const char *names[GNUNET_NZL (max_names)];
    enum GNUNET_DB_QueryStatus qs;
    size_t num_names = 0;

    buf = GNUNET_strdup (all_names);
    for (const char *tok = strtok (buf,
                                   " ");
         NULL != tok;
         tok = strtok (NULL,
                       " "))
    {
      GNUNET_assert (num_names < max_names);
      names[num_names++] = tok;
    }
    qs = TEH_plugin->select_aml_statistics (
      TEH_plugin->cls,
      num_names,
      names,
      start_date,
      end_date,
      &add_stat,
      stats);
    GNUNET_free (buf);
    switch (qs)
    {
    case GNUNET_DB_STATUS_HARD_ERROR:
    case GNUNET_DB_STATUS_SOFT_ERROR:
      GNUNET_break (0);
      return TALER_MHD_reply_with_error (
        rc->connection,
        MHD_HTTP_INTERNAL_SERVER_ERROR,
        TALER_EC_GENERIC_DB_FETCH_FAILED,
        "select_aml_statistics");
    case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
      return TALER_MHD_reply_static (
        rc->connection,
        MHD_HTTP_NO_CONTENT,
        NULL,
        NULL,
        0);
    case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
      break;
    }
    return TALER_MHD_REPLY_JSON_PACK (
      rc->connection,
      MHD_HTTP_OK,
      GNUNET_JSON_pack_array_steal ("statistics",
                                    stats));
  }
}


/* end of taler-exchange-httpd_aml-statistics_get.c */
