/*
   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 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 General Public License for more details.

   You should have received a copy of the GNU General Public License along with
   TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */
/**
 * @file backenddb/pg_lookup_statistics_amount_by_interval.c
 * @brief Implementation of the lookup_statistics_amount_by_interval function for Postgres
 * @author Martin Schanzenbach
 */
#include "platform.h"
#include <taler/taler_error_codes.h>
#include <taler/taler_dbevents.h>
#include <taler/taler_pq_lib.h>
#include "pg_lookup_statistics_amount_by_interval.h"
#include "pg_helper.h"
#include "taler_merchantdb_plugin.h"


/**
 * Context used for TMH_PG_lookup_statistics_amount().
 */
struct LookupAmountStatisticsContext
{
  /**
   * Function to call with the results.
   */
  TALER_MERCHANTDB_AmountByIntervalStatisticsCallback cb;

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

  /**
   * Did database result extraction fail?
   */
  bool extract_failed;

  /**
   * Description of statistic
   */
  char*description;
};

/**
 * Function to be called with the results of a SELECT statement
 * that has returned @a num_results results about statistics.
 *
 * @param[in,out] cls of type `struct LookupTokenFamiliesContext *`
 * @param result the postgres result
 * @param num_results the number of results in @a result
 */
static void
lookup_statistics_amount_by_interval_desc_cb (void *cls,
                                              PGresult *result,
                                              unsigned int num_results)
{
  struct LookupAmountStatisticsContext *tflc = cls;

  for (unsigned int i = 0; i < num_results; i++)
  {
    char *description;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_string ("description",
                                    &description),
      GNUNET_PQ_result_spec_end
    };

    if (GNUNET_OK !=
        GNUNET_PQ_extract_result (result,
                                  rs,
                                  i))
    {
      GNUNET_break (0);
      tflc->extract_failed = true;
      return;
    }

    tflc->description = GNUNET_strdup (description);

    GNUNET_PQ_cleanup_result (rs);
  }
}


/**
 * Function to be called with the results of a SELECT statement
 * that has returned @a num_results results about statistics.
 *
 * @param[in,out] cls of type `struct LookupTokenFamiliesContext *`
 * @param result the postgres result
 * @param num_results the number of results in @a result
 */
static void
lookup_statistics_amount_by_interval_cb (void *cls,
                                         PGresult *result,
                                         unsigned int num_results)
{
  struct LookupAmountStatisticsContext *tflc = cls;
  struct TALER_Amount *amounts = NULL;
  char *resp_desc = NULL;
  uint64_t cur_interval_start_ago = UINT64_MAX;
  unsigned int amounts_len = 0;

  for (unsigned int i = 0; i < num_results; i++)
  {
    struct TALER_Amount cumulative_amount;
    uint64_t interval_start_ago;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_uint64 ("range",
                                    &interval_start_ago),
      TALER_PQ_result_spec_amount_with_currency ("rvalue",
                                                 &cumulative_amount),
      GNUNET_PQ_result_spec_end
    };

    if (GNUNET_OK !=
        GNUNET_PQ_extract_result (result,
                                  rs,
                                  i))
    {
      GNUNET_break (0);
      tflc->extract_failed = true;
      return;
    }

    /* Call callback if the bucket changed */
    if ( (interval_start_ago != cur_interval_start_ago) &&
         (i > 0) )
    {
      struct GNUNET_TIME_Timestamp interval_start;

      interval_start = GNUNET_TIME_timestamp_get ();
      interval_start.abs_time.abs_value_us -= interval_start_ago * 1000 * 1000;
      tflc->cb (tflc->cb_cls,
                resp_desc,
                interval_start,
                amounts_len,
                amounts);
      GNUNET_array_grow (amounts,
                         amounts_len,
                         0);
      GNUNET_free (resp_desc);
    }
    cur_interval_start_ago = interval_start_ago;
    GNUNET_array_append (amounts,
                         amounts_len,
                         cumulative_amount);
    GNUNET_PQ_cleanup_result (rs);
  }
  if (0 != amounts_len)
  {
    struct GNUNET_TIME_Timestamp interval_start;

    interval_start = GNUNET_TIME_timestamp_from_s (cur_interval_start_ago);
    tflc->cb (tflc->cb_cls,
              resp_desc,
              interval_start,
              amounts_len,
              amounts);
    GNUNET_array_grow (amounts,
                       amounts_len,
                       0);
    GNUNET_free (resp_desc);
  }
}


enum GNUNET_DB_QueryStatus
TMH_PG_lookup_statistics_amount_by_interval (
  void *cls,
  const char *instance_id,
  const char *slug,
  TALER_MERCHANTDB_AmountByIntervalStatisticsCallback cb,
  void *cb_cls)
{
  struct PostgresClosure *pg = cls;
  struct LookupAmountStatisticsContext context = {
    .cb = cb,
    .cb_cls = cb_cls,
    /* Can be overwritten by the lookup_statistics_amount_by_interval_cb */
    .extract_failed = false,
    .description = NULL
  };
  struct GNUNET_PQ_QueryParam descParams[] = {
    GNUNET_PQ_query_param_string (slug),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_string (instance_id),
    GNUNET_PQ_query_param_string (slug),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  PREPARE (pg,
           "lookup_statistics_amount_by_interval_description",
           "SELECT description"
           " FROM merchant_statistic_interval_meta"
           " WHERE slug=$1 LIMIT 1");
  qs = GNUNET_PQ_eval_prepared_multi_select (
    pg->conn,
    "lookup_statistics_amount_by_interval_description",
    descParams,
    &lookup_statistics_amount_by_interval_desc_cb,
    &context);
  /* If there was an error inside the cb, return a hard error. */
  if (context.extract_failed)
  {
    GNUNET_break (0);
    return GNUNET_DB_STATUS_HARD_ERROR;
  }
  PREPARE (pg,
           "lookup_statistics_amount_by_interval",
           "SELECT *"
           " FROM merchant_statistic_interval_amount_get($2,$1)");
  qs = GNUNET_PQ_eval_prepared_multi_select (
    pg->conn,
    "lookup_statistics_amount_by_interval",
    params,
    &lookup_statistics_amount_by_interval_cb,
    &context);
  if (NULL != context.description)
    GNUNET_free (context.description);
  /* If there was an error inside the cb, return a hard error. */
  if (context.extract_failed)
  {
    GNUNET_break (0);
    return GNUNET_DB_STATUS_HARD_ERROR;
  }
  return qs;
}
