/*
   This file is part of TALER
   Copyright (C) 2024 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_iterate_submitted_receipts.c
 * @brief Implementation of the iterate_submitted_receipts function for Postgres
 * @author Johannes Casaburi
 */
#include <donau_config.h>
#include <taler/taler_error_codes.h>
#include <taler/taler_dbevents.h>
#include <taler/taler_pq_lib.h>
#include "pg_iterate_submitted_receipts.h"
#include "pg_helper.h"
#include "donaudb_plugin.h"
#include "donau_pq_lib.h"


enum GNUNET_DB_QueryStatus
DH_PG_iterate_submitted_receipts (
  void *cls,
  const uint64_t donation_year,
  const struct DONAU_HashDonorTaxId *h_donor_tax_id,
  struct TALER_Amount *total_donations)
{
  struct PostgresClosure *pg = cls;

  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_uint64 (&donation_year),
    GNUNET_PQ_query_param_auto_from_type (h_donor_tax_id),
    GNUNET_PQ_query_param_end
  };
  uint64_t valueSum = 0;
  uint64_t fractionSum = 0;
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_uint64 ("valueSum",
                                  &valueSum),
    GNUNET_PQ_result_spec_uint64 ("fractionSum",
                                  &fractionSum),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  PREPARE (pg,
           "lookup_submitted_receipts",
           "SELECT "
           " CAST(SUM((donation_units.value).val) AS INT8) AS valueSum"
           ",CAST(SUM(CAST((donation_units.value).frac AS INT8)) AS INT8) AS fractionSum"
           " FROM receipts_submitted ref"
           " JOIN donation_units USING (h_donation_unit_pub)"
           " WHERE donation_year=$1"
           " AND h_tax_number=$2");
  qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                 "lookup_submitted_receipts",
                                                 params,
                                                 rs);
  if (qs < 0)
    return qs;
  valueSum += fractionSum / TALER_AMOUNT_FRAC_BASE;
  fractionSum %= TALER_AMOUNT_FRAC_BASE;
  TALER_amount_set_zero (pg->currency,
                         total_donations);
  total_donations->value = valueSum;
  total_donations->fraction = fractionSum;
  return qs;
}
