/*
   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_counter_by_bucket2.c
 * @brief Implementation of the lookup_statistics_counter_by_bucket2 function for Postgres
 * @author Christian Grothoff
 */
#include "taler/platform.h"
#include <taler/taler_error_codes.h>
#include <taler/taler_dbevents.h>
#include <taler/taler_pq_lib.h>
#include "pg_lookup_statistics_counter_by_bucket2.h"
#include "pg_helper.h"

/**
 * Context used for TMH_PG_lookup_statistics_counter_by_bucket2().
 */
struct LookupCounterStatisticsContext2
{
  /**
   * Function to call with the results.
   */
  TALER_MERCHANTDB_CounterByBucketStatisticsCallback2 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 LookupCounterStatisticsContext2 *`
 * @param result the postgres result
 * @param num_results the number of results in @a result
 */
static void
lookup_statistics_counter_by_bucket_cb2 (void *cls,
                                         PGresult *result,
                                         unsigned int num_results)
{
  struct LookupCounterStatisticsContext2 *tflc = cls;
  struct PostgresClosure *pg = tflc->pg;

  for (unsigned int i = 0; i < num_results; i++)
  {
    size_t num_slugs;
    char *slugs;
    size_t num_counters;
    uint64_t *counters;
    uint64_t bucket_start_epoch;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_uint64 ("bucket_start",
                                    &bucket_start_epoch),
      GNUNET_PQ_result_spec_array_uint64 (pg->conn,
                                          "counters",
                                          &num_counters,
                                          &counters),
      GNUNET_PQ_result_spec_array_string (pg->conn,
                                          "slugs",
                                          &num_slugs,
                                          &slugs),
      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;
    }
    if (num_slugs != num_counters)
    {
      GNUNET_break (0);
      tflc->extract_failed = true;
      GNUNET_PQ_cleanup_result (rs);
      return;
    }
    {
      const char *slugptrs[num_slugs];
      const char *pos = slugs;

      for (size_t j = 0; j<num_slugs; j++)
      {
        slugptrs[j] = pos;
        pos += strlen (pos) + 1;
      }

      bucket_start = GNUNET_TIME_timestamp_from_s (bucket_start_epoch);
      tflc->cb (tflc->cb_cls,
                bucket_start,
                num_slugs,
                slugptrs,
                counters);
    }
    GNUNET_PQ_cleanup_result (rs);
  }
}


enum GNUNET_DB_QueryStatus
TMH_PG_lookup_statistics_counter_by_bucket2 (
  void *cls,
  const char *instance_id,
  const char *prefix,
  const char *granularity,
  uint64_t counter,
  TALER_MERCHANTDB_CounterByBucketStatisticsCallback2 cb,
  void *cb_cls)
{
  struct PostgresClosure *pg = cls;
  struct LookupCounterStatisticsContext2 context = {
    .cb = cb,
    .cb_cls = cb_cls,
    /* Can be overwritten by the lookup_statistics_counter_by_bucket_cb2 */
    .extract_failed = false,
    .pg = pg
  };
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_string (instance_id),
    GNUNET_PQ_query_param_string (prefix),
    GNUNET_PQ_query_param_string (granularity),
    GNUNET_PQ_query_param_uint64 (&counter),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  PREPARE (pg,
           "lookup_statistics_counter_by_bucket2",
           "SELECT"
           " msbc.bucket_start"
           ",ARRAY_AGG(msbm.slug) AS slugs"
           ",ARRAY_AGG(msbc.cumulative_number) AS counters"
           "  FROM merchant_statistic_bucket_counter msbc"
           "  JOIN merchant_statistic_bucket_meta msbm"
           "    USING (bmeta_serial_id)"
           "  JOIN merchant_instances mi"
           "    USING (merchant_serial)"
           " WHERE mi.merchant_id=$1"
           "   AND msbm.slug LIKE $2"
           "   AND msbc.bucket_range=$3::TEXT::statistic_range"
           "   AND msbm.stype = 'number'"
           " GROUP BY msbc.bucket_start"
           " ORDER BY msbc.bucket_start DESC"
           " LIMIT $4");
  qs = GNUNET_PQ_eval_prepared_multi_select (
    pg->conn,
    "lookup_statistics_counter_by_bucket2",
    params,
    &lookup_statistics_counter_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;
}
