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


/**
 * Closure for #handle_aml_result.
 */
struct SelectTransferContext
{
  /**
   * Function to call on each result.
   */
  TALER_EXCHANGEDB_AmlTransferCallback cb;

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

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

  /**
   * Set to #GNUNET_SYSERR on serious errors.
   */
  enum GNUNET_GenericReturnValue status;
};


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

  for (unsigned int i = 0; i<num_results; i++)
  {
    char *payto_uri;
    uint64_t rowid;
    struct GNUNET_TIME_Absolute execution_time;
    struct TALER_Amount amount;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_uint64 ("serial_id",
                                    &rowid),
      GNUNET_PQ_result_spec_string ("payto_uri",
                                    &payto_uri),
      GNUNET_PQ_result_spec_absolute_time ("execution_time",
                                           &execution_time),
      TALER_PQ_RESULT_SPEC_AMOUNT ("amount",
                                   &amount),
      GNUNET_PQ_result_spec_end
    };

    if (GNUNET_OK !=
        GNUNET_PQ_extract_result (result,
                                  rs,
                                  i))
    {
      GNUNET_break (0);
      stc->status = GNUNET_SYSERR;
      return;
    }
    stc->cb (stc->cb_cls,
             rowid,
             payto_uri,
             execution_time,
             &amount);
    GNUNET_PQ_cleanup_result (rs);
  }
}


enum GNUNET_DB_QueryStatus
TEH_PG_select_exchange_debit_transfers (
  void *cls,
  const struct TALER_Amount *threshold,
  uint64_t offset,
  int64_t limit,
  TALER_EXCHANGEDB_AmlTransferCallback cb,
  void *cb_cls)
{
  struct PostgresClosure *pg = cls;
  struct SelectTransferContext stc = {
    .pg = pg,
    .cb = cb,
    .cb_cls = cb_cls,
    .status = GNUNET_OK
  };
  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_end
  };
  enum GNUNET_DB_QueryStatus qs;

  PREPARE (pg,
           "select_exchange_debit_transfers_inc",
           "SELECT"
           " wo.wireout_uuid AS serial_id"
           ",wt.payto_uri"
           ",wo.execution_date AS execution_time"
           ",wo.amount"
           " FROM wire_out wo"
           " LEFT JOIN wire_targets wt"
           "   USING (wire_target_h_payto)"
           " WHERE (wo.wireout_uuid > $1)"
           " ORDER BY wo.wireout_uuid ASC"
           " LIMIT $2");
  PREPARE (pg,
           "select_exchange_debit_transfers_dec",
           "SELECT"
           " wo.wireout_uuid AS serial_id"
           ",wt.payto_uri"
           ",wo.execution_date AS execution_time"
           ",wo.amount"
           " FROM wire_out wo"
           " LEFT JOIN wire_targets wt"
           "   USING (wire_target_h_payto)"
           " WHERE (wo.wireout_uuid < $1)"
           " ORDER BY wo.wireout_uuid DESC"
           " LIMIT $2");
  qs = GNUNET_PQ_eval_prepared_multi_select (
    pg->conn,
    (limit > 0)
    ? "select_exchange_debit_transfers_inc"
    : "select_exchange_debit_transfers_dec",
    params,
    &handle_transfer_result,
    &stc);
  if (GNUNET_OK != stc.status)
    return GNUNET_DB_STATUS_HARD_ERROR;
  return qs;
}
