/*
   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 exchangedb/get_aggregation_deferral_by_wtid.c
 * @brief Implementation of the get_aggregation_deferral_by_wtid function for Postgres
 * @author Christian Grothoff
 */
#include "taler/taler_error_codes.h"
#include "taler/taler_pq_lib.h"
#include "exchange-database/get_aggregation_deferral_by_wtid.h"
#include "helper.h"


enum GNUNET_DB_QueryStatus
TALER_EXCHANGEDB_get_aggregation_deferral_by_wtid (
  struct TALER_EXCHANGEDB_PostgresContext *pg,
  const struct TALER_WireTransferIdentifierRawP *wtid,
  struct TALER_Amount *amount,
  enum TALER_EXCHANGEDB_DeferralReason *reason,
  uint64_t *kyc_requirement_row,
  struct GNUNET_TIME_Timestamp *deferral_time)
{
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (wtid),
    GNUNET_PQ_query_param_end
  };
  uint32_t reason32;
  struct GNUNET_PQ_ResultSpec rs[] = {
    TALER_PQ_RESULT_SPEC_AMOUNT ("amount",
                                 amount),
    GNUNET_PQ_result_spec_uint32 ("deferral_reason",
                                  &reason32),
    GNUNET_PQ_result_spec_uint64 ("legitimization_requirement_serial_id",
                                  kyc_requirement_row),
    GNUNET_PQ_result_spec_timestamp ("deferral_time",
                                     deferral_time),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  PREPARE (pg,
           "get_aggregation_deferral_by_wtid",
           "SELECT"
           " amount"
           ",deferral_reason"
           ",legitimization_requirement_serial_id"
           ",deferral_time"
           " FROM aggregation_deferrals"
           " WHERE wtid_raw=$1"
           " ORDER BY aggregation_deferral_serial_id DESC"
           " LIMIT 1;");
  qs = GNUNET_PQ_eval_prepared_singleton_select (
    pg->conn,
    "get_aggregation_deferral_by_wtid",
    params,
    rs);
  if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT == qs)
    *reason = (enum TALER_EXCHANGEDB_DeferralReason) reason32;
  return qs;
}
