/*
   This file is part of TALER
   Copyright (C) 2024, 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 donaudb/pg_lookup_issued_receipts.c
 * @brief Implementation of the lookup_issued_receipts function for Postgres
 * @author Lukas Matyja
 */
#include <donau_config.h>
#include <taler/taler_error_codes.h>
#include <taler/taler_dbevents.h>
#include <taler/taler_pq_lib.h>
#include "pg_lookup_issued_receipts.h"
#include "pg_helper.h"
#include "donau_pq_lib.h"

enum GNUNET_DB_QueryStatus
DH_PG_lookup_issued_receipts (
  void *cls,
  struct DONAU_DonationReceiptHashP *h_receipts,
  struct DONAUDB_IssuedReceiptsMetaData *meta)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (h_receipts),
    GNUNET_PQ_query_param_end
  };
  struct DONAU_BlindedDonationUnitSignature *du_sigs;
  size_t num_sigs;
  struct GNUNET_PQ_ResultSpec rs[] = {
    DONAU_PQ_result_spec_array_blinded_donation_unit_sig (
      pg->conn,
      "blinded_sig",
      &num_sigs,
      &du_sigs),
    TALER_PQ_RESULT_SPEC_AMOUNT ("amount",
                                 &meta->amount),
    GNUNET_PQ_result_spec_uint64 ("charity_id",
                                  &meta->charity_id),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  PREPARE (pg,
           "lookup_issued_receipts",
           "SELECT "
           " blinded_sig"
           " ,amount"
           " ,charity_id"
           " FROM receipts_issued"
           " WHERE receipt_hash=$1;");
  qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                 "lookup_issued_receipts",
                                                 params,
                                                 rs);
  if (qs > 0)
  {
    /* prevent the result cleanup from freeing the signatures */
    meta->num_sig = num_sigs;
    meta->blinded_sigs = du_sigs;
    num_sigs = 0;
    du_sigs = NULL;
  }
  GNUNET_PQ_cleanup_result (rs);
  return qs;
}
