/*
   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 src/backenddb/iterate_statistic_bucket_amounts_by_range.c
 * @brief Implementation of the iterate_statistic_bucket_amounts_by_range function for Postgres
 * @author Christian Grothoff
 */
#include "platform.h"
#include <taler/taler_pq_lib.h>
#include "merchant-database/iterate_statistic_bucket_amounts_by_range.h"
#include "helper.h"


/**
 * Context used for TALER_MERCHANTDB_iterate_statistic_bucket_amounts_by_range().
 */
struct LookupAmountStatisticsContext2
{
  /**
   * Function to call with the results.
   */
  TALER_MERCHANTDB_AmountByBucketRangeStatisticsCallback cb;

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

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

  /**
   * Postgres context for array lookups
   */
  struct TALER_MERCHANTDB_PostgresContext *pg;
};


/**
 * Function to be called with the results of a SELECT statement
 * that has returned @a num_results results about token families.
 *
 * @param[in,out] cls of type `struct LookupAmountStatisticsContext2 *`
 * @param result the postgres result
 * @param num_results the number of results in @a result
 */
static void
lookup_statistics_amount_by_bucket_cb2 (void *cls,
                                        PGresult *result,
                                        unsigned int num_results)
{
  struct LookupAmountStatisticsContext2 *tflc = cls;
  struct TALER_MERCHANTDB_PostgresContext *pg = tflc->pg;

  for (unsigned int i = 0; i < num_results; i++)
  {
    struct TALER_Amount *amounts;
    size_t num_amounts;
    uint64_t bucket_start_epoch;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_uint64 ("bucket_start",
                                    &bucket_start_epoch),
      TALER_PQ_result_spec_array_amount_with_currency (pg->conn,
                                                       "merchant",
                                                       "cumulative_amounts",
                                                       &num_amounts,
                                                       &amounts),
      GNUNET_PQ_result_spec_end
    };
    struct GNUNET_TIME_Timestamp bucket_start;

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

    bucket_start = GNUNET_TIME_timestamp_from_s (bucket_start_epoch);
    tflc->cb (tflc->cb_cls,
              bucket_start,
              num_amounts,
              amounts);
    GNUNET_PQ_cleanup_result (rs);
  }
}


enum GNUNET_DB_QueryStatus
TALER_MERCHANTDB_iterate_statistic_bucket_amounts_by_range (
  struct TALER_MERCHANTDB_PostgresContext *pg,
  const char *instance_id,
  const char *slug,
  const char *granularity,
  uint64_t counter,
  TALER_MERCHANTDB_AmountByBucketRangeStatisticsCallback cb,
  void *cb_cls)
{
  struct LookupAmountStatisticsContext2 context = {
    .cb = cb,
    .cb_cls = cb_cls,
    /* Can be overwritten by the lookup_statistics_amount_by_bucket_cb2 */
    .extract_failed = false,
    .pg = pg,
  };
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_string (slug),
    GNUNET_PQ_query_param_string (granularity),
    GNUNET_PQ_query_param_uint64 (&counter),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  GNUNET_assert (NULL != pg->current_merchant_id);
  GNUNET_assert (0 == strcmp (instance_id,
                              pg->current_merchant_id));
  TMH_PQ_prepare_anon (pg,
                       "SELECT"
                       " msba.bucket_start"
                       ",ARRAY_AGG ("
                       "   ROW(msba.cumulative_value::INT8, msba.cumulative_frac::INT4, msba.curr)::merchant.taler_amount_currency"
                       " ) AS cumulative_amounts"
                       " FROM merchant_statistic_bucket_meta msbm"
                       " JOIN merchant_statistic_bucket_amount msba"
                       "   USING (bmeta_serial_id)"
                       " WHERE msbm.slug=$1"
                       "   AND msba.bucket_range=$2::TEXT::merchant.statistic_range"
                       "   AND msbm.stype='amount'"
                       " GROUP BY msba.bucket_start"
                       " ORDER BY msba.bucket_start DESC"
                       " LIMIT $3;");
  qs = GNUNET_PQ_eval_prepared_multi_select (
    pg->conn,
    "",
    params,
    &lookup_statistics_amount_by_bucket_cb2,
    &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;
  }
  return qs;
}
