/*
   This file is part of TALER
   Copyright (C) 2026 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/exchangedb/iterate_aggregation_wtids_above_serial_id.c
 * @brief Implementation of the iterate_aggregation_wtids_above_serial_id function for Postgres
 * @author Christian Grothoff
 */
#include "taler/taler_pq_lib.h"
#include "helper.h"
#include "exchange-database/iterate_aggregation_wtids_above_serial_id.h"


/**
 * Closure for #aggregation_wtid_cb().
 */
struct AggregationWtidContext
{
  /**
   * Function to call for each aggregation.
   */
  TALER_EXCHANGEDB_AggregationWtidCallback cb;

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

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


/**
 * Helper function for
 * #TALER_EXCHANGEDB_iterate_aggregation_wtids_above_serial_id().
 * To be called with the results of a SELECT statement
 * that has returned @a num_results results.
 *
 * @param cls closure of type `struct AggregationWtidContext *`
 * @param result the postgres result
 * @param num_results the number of results in @a result
 */
static void
aggregation_wtid_cb (void *cls,
                     PGresult *result,
                     unsigned int num_results)
{
  struct AggregationWtidContext *awc = cls;

  for (unsigned int i = 0; i < num_results; i++)
  {
    uint64_t rowid;
    struct TALER_WireTransferIdentifierRawP wtid;
    struct TALER_FullPaytoHashP wire_target_h_payto;
    bool pending;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_uint64 ("aggregation_serial_id",
                                    &rowid),
      GNUNET_PQ_result_spec_auto_from_type ("wtid_raw",
                                            &wtid),
      GNUNET_PQ_result_spec_auto_from_type ("wire_target_h_payto",
                                            &wire_target_h_payto),
      GNUNET_PQ_result_spec_bool ("pending",
                                  &pending),
      GNUNET_PQ_result_spec_end
    };
    enum GNUNET_GenericReturnValue rval;

    if (GNUNET_OK !=
        GNUNET_PQ_extract_result (result,
                                  rs,
                                  i))
    {
      GNUNET_break (0);
      awc->qs = GNUNET_DB_STATUS_HARD_ERROR;
      return;
    }
    awc->qs = i + 1;
    rval = awc->cb (awc->cb_cls,
                    rowid,
                    &wtid,
                    &wire_target_h_payto,
                    pending);
    GNUNET_PQ_cleanup_result (rs);
    if (GNUNET_OK != rval)
      break;
  }
}


enum GNUNET_DB_QueryStatus
TALER_EXCHANGEDB_iterate_aggregation_wtids_above_serial_id (
  struct TALER_EXCHANGEDB_PostgresContext *pg,
  uint64_t serial_id,
  TALER_EXCHANGEDB_AggregationWtidCallback cb,
  TALER_EXCHANGEDB_AGGREGATION_WTID_RESULT_CLOSURE *cb_cls)
{
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_uint64 (&serial_id),
    GNUNET_PQ_query_param_end
  };
  struct AggregationWtidContext awc = {
    .cb = cb,
    .cb_cls = cb_cls
  };
  enum GNUNET_DB_QueryStatus qs;

  /* Rows that already have their `wire_out' are returned as well, flagged as
     not pending: the caller needs every serial ID to be able to advance its
     cursor past them, but knowing here that the transfer happened saves it
     from asking #TALER_EXCHANGEDB_get_pending_aggregation() -- a full
     recomputation of the transfer -- once per wire transfer the exchange ever
     made, which is what the first run after an upgrade would otherwise do. */
  PREPARE (pg,
           "iterate_aggregation_wtids_above_serial_id",
           "SELECT"
           " atr.aggregation_serial_id"
           ",atr.wtid_raw"
           ",bdep.wire_target_h_payto"
           ",NOT EXISTS ("
           "   SELECT 1"
           "     FROM wire_out wo"
           "    WHERE wo.wtid_raw=atr.wtid_raw"
           " ) AS pending"
           " FROM aggregation_tracking atr"
           " JOIN batch_deposits bdep"
           "   USING (batch_deposit_serial_id)"
           " WHERE atr.aggregation_serial_id>=$1"
           " ORDER BY atr.aggregation_serial_id ASC;");
  qs = GNUNET_PQ_eval_prepared_multi_select (
    pg->conn,
    "iterate_aggregation_wtids_above_serial_id",
    params,
    &aggregation_wtid_cb,
    &awc);
  if (qs > 0)
    return awc.qs;
  GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR != qs);
  return qs;
}
