/*
   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_bucket.c
 * @brief Implementation of the lookup_statistics_amount_by_bucket 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_bucket.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_AmountByBucketStatisticsCallback cb;

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

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

  /**
   * Postgres context for array lookups
   */
  struct PostgresClosure *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 LookupTokenFamiliesContext *`
 * @param result the postgres result
 * @param num_results the number of results in @a result
 */
static void
lookup_statistics_amount_by_bucket_cb (void *cls,
                                       PGresult *result,
                                       unsigned int num_results)
{
  struct LookupAmountStatisticsContext *tflc = cls;
  struct TALER_Amount *amounts = NULL;
  char *resp_range = NULL;
  char *resp_desc = NULL;
  uint64_t cur_bucket_start_epoch;
  uint64_t cur_bucket_end_epoch;
  uint64_t bmeta_id_current;
  unsigned int amounts_len = 0;

  for (unsigned int i = 0; i < num_results; i++)
  {
    struct TALER_Amount cumulative_amount;
    char *description;
    char *bucket_range;
    uint64_t bmeta_id;
    uint64_t bucket_start_epoch;
    uint64_t bucket_end_epoch;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_uint64 ("bmeta_serial_id",
                                    &bmeta_id),
      GNUNET_PQ_result_spec_string ("description",
                                    &description),
      GNUNET_PQ_result_spec_uint64 ("bucket_start",
                                    &bucket_start_epoch),
      GNUNET_PQ_result_spec_uint64 ("bucket_end",
                                    &bucket_end_epoch),
      GNUNET_PQ_result_spec_string ("bucket_range",
                                    &bucket_range),
      TALER_PQ_result_spec_amount_with_currency ("cumulative_amount",
                                                 &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 ( (NULL != resp_desc) &&
         ( (bmeta_id != bmeta_id_current) ||
           (bucket_start_epoch != cur_bucket_start_epoch) ||
           (0 != strcasecmp (resp_range,
                             bucket_range)) ) )
    {
      struct GNUNET_TIME_Timestamp bucket_start;
      struct GNUNET_TIME_Timestamp bucket_end;

      bucket_start = GNUNET_TIME_timestamp_from_s (cur_bucket_start_epoch);
      bucket_end = GNUNET_TIME_timestamp_from_s (cur_bucket_end_epoch);
      tflc->cb (tflc->cb_cls,
                resp_desc,
                bucket_start,
                bucket_end,
                resp_range,
                amounts_len,
                amounts);
      GNUNET_free (resp_range);
      GNUNET_free (resp_desc);
      GNUNET_array_grow (amounts,
                         amounts_len,
                         0);
    }
    if (NULL == resp_desc)
    {
      cur_bucket_end_epoch = bucket_end_epoch;
      cur_bucket_start_epoch = bucket_start_epoch;
      resp_range = GNUNET_strdup (bucket_range);
      resp_desc = GNUNET_strdup (description);
      bmeta_id_current = bmeta_id;
    }
    GNUNET_array_append (amounts,
                         amounts_len,
                         cumulative_amount);
    GNUNET_PQ_cleanup_result (rs);
  }
  if (0 != amounts_len)
  {
    struct GNUNET_TIME_Timestamp bucket_start;
    struct GNUNET_TIME_Timestamp bucket_end;

    bucket_start = GNUNET_TIME_timestamp_from_s (cur_bucket_start_epoch);
    bucket_end = GNUNET_TIME_timestamp_from_s (cur_bucket_end_epoch);
    tflc->cb (tflc->cb_cls,
              resp_desc,
              bucket_start,
              bucket_end,
              resp_range,
              amounts_len,
              amounts);
    GNUNET_array_grow (amounts,
                       amounts_len,
                       0);
    GNUNET_free (resp_range);
    GNUNET_free (resp_desc);
  }
}


enum GNUNET_DB_QueryStatus
TMH_PG_lookup_statistics_amount_by_bucket (
  void *cls,
  const char *instance_id,
  const char *slug,
  TALER_MERCHANTDB_AmountByBucketStatisticsCallback 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_bucket_cb */
    .extract_failed = false,
    .pg = pg,
  };
  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_bucket",
           "SELECT"
           " bmeta_serial_id"
           ",description"
           ",bucket_start"
           ",bucket_range::TEXT"
           ",merchant_statistics_bucket_end(bucket_start, bucket_range) AS bucket_end"
           ",(cumulative_value,cumulative_frac,curr)::taler_amount_currency AS cumulative_amount"
           " FROM merchant_statistic_bucket_amount"
           " JOIN merchant_statistic_bucket_meta"
           "   USING (bmeta_serial_id)"
           " JOIN merchant_instances"
           "   USING (merchant_serial)"
           " WHERE merchant_instances.merchant_id=$1"
           "   AND merchant_statistic_bucket_meta.slug=$2"
           "   AND merchant_statistic_bucket_meta.stype='amount'");
  qs = GNUNET_PQ_eval_prepared_multi_select (
    pg->conn,
    "lookup_statistics_amount_by_bucket",
    params,
    &lookup_statistics_amount_by_bucket_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;
  }
  return qs;
}
