/*
   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 auditordb/pg_select_early_aggregations.c
 * @brief Implementation of the select_early_aggregations 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_select_early_aggregations.h"
#include "pg_helper.h"


/**
 * Closure for #early_aggregation_cb().
 */
struct EarlyAggregationContext
{

  /**
   * Function to call for each early aggregation.
   */
  TALER_AUDITORDB_EarlyAggregationsCallback cb;

  /**
   * Closure for @e cb
   */
  void *cb_cls;

  /**
   * Plugin context.
   */
  struct PostgresClosure *pg;

  /**
   * Query status to return.
   */
  enum GNUNET_DB_QueryStatus qs;
};


/**
 * Helper function for #TAH_PG_select_purse_expired().
 * To be called with the results of a SELECT statement
 * that has returned @a num_results results.
 *
 * @param cls closure of type `struct EarlyAggregationContext *`
 * @param result the postgres result
 * @param num_results the number of results in @a result
 */
static void
early_aggregation_cb (void *cls,
                      PGresult *result,
                      unsigned int num_results)
{
  struct EarlyAggregationContext *eic = cls;
  struct PostgresClosure *pg = eic->pg;

  for (unsigned int i = 0; i < num_results; i++)
  {
    struct TALER_AUDITORDB_EarlyAggregation ea;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_uint64 ("row_id",
                                    &ea.row_id),
      GNUNET_PQ_result_spec_uint64 ("batch_deposit_serial_id",
                                    &ea.batch_deposit_serial_id),
      GNUNET_PQ_result_spec_uint64 ("tracking_serial_id",
                                    &ea.tracking_serial_id),
      TALER_PQ_RESULT_SPEC_AMOUNT ("amount",
                                   &ea.total),
      GNUNET_PQ_result_spec_bool ("suppressed",
                                  &ea.suppressed),
      GNUNET_PQ_result_spec_end
    };

    /* just to be safe in case the structure changes */
    memset (&ea,
            0,
            sizeof (ea));
    if (GNUNET_OK !=
        GNUNET_PQ_extract_result (result,
                                  rs,
                                  i))
    {
      GNUNET_break (0);
      eic->qs = GNUNET_DB_STATUS_HARD_ERROR;
      return;
    }
    eic->cb (eic->cb_cls,
             &ea);
  }
  eic->qs = num_results;
}


enum GNUNET_DB_QueryStatus
TAH_PG_select_early_aggregations (
  void *cls,
  int64_t limit,
  uint64_t offset,
  bool return_suppressed,
  TALER_AUDITORDB_EarlyAggregationsCallback cb,
  void *cb_cls)
{
  struct PostgresClosure *pg = cls;
  uint64_t ulimit = (limit < 0) ? -limit : limit;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_uint64 (&offset),
    GNUNET_PQ_query_param_uint64 (&ulimit),
    GNUNET_PQ_query_param_bool (return_suppressed),
    GNUNET_PQ_query_param_end
  };
  struct EarlyAggregationContext eic = {
    .cb = cb,
    .cb_cls = cb_cls,
    .pg = pg
  };
  enum GNUNET_DB_QueryStatus qs;

  PREPARE (pg,
           "auditor_select_early_aggregations_asc",
           "SELECT"
           " row_id"
           ",batch_deposit_serial_id"
           ",tracking_serial_id"
           ",amount"
           ",suppressed"
           " FROM auditor_early_aggregations"
           " WHERE row_id > $1"
           "   AND ($3 OR NOT suppressed)"
           " ORDER BY row_id ASC"
           " LIMIT $2;");
  PREPARE (pg,
           "auditor_select_early_aggregations_desc",
           "SELECT"
           " row_id"
           ",batch_deposit_serial_id"
           ",tracking_serial_id"
           ",amount"
           ",suppressed"
           " FROM auditor_early_aggregations"
           " WHERE row_id < $1"
           "   AND ($3 OR NOT suppressed)"
           " ORDER BY row_id DESC"
           " LIMIT $2;");
  qs = GNUNET_PQ_eval_prepared_multi_select (
    pg->conn,
    (limit < 0)
    ? "auditor_select_early_aggregations_desc"
    : "auditor_select_early_aggregations_asc ",
    params,
    &early_aggregation_cb,
    &eic);
  if (0 > qs)
    return qs;
  GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR != eic.qs);
  return eic.qs;
}
