/*
   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_get_charities.c
 * @brief Implementation of the lookup_donation_unit_key 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_get_charities.h"
#include "pg_helper.h"


/**
 * Closure for #get_charities_cb().
 */
struct GetCharitiesContext
{
  /**
   * Function to call per result.
   */
  DONAUDB_GetCharitiesCallback cb;

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

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

  /**
   * Number of results processed.
   */
  enum GNUNET_DB_QueryStatus qs;

};


/**
 * Invoke the callback for each result.
 *
 * @param cls a `struct MissingWireContext *`
 * @param result SQL result
 * @param num_results number of rows in @a result
 */
static void
get_charities_cb (void *cls,
                  PGresult *result,
                  unsigned int num_results)
{
  struct GetCharitiesContext *ctx = cls;
  struct PostgresClosure *pg = ctx->pg;

  for (unsigned int i = 0; i < num_results; i++)
  {
    uint64_t charity_id;
    struct DONAU_CharityPublicKeyP charity_pub;
    char *charity_name;
    struct TALER_Amount max_per_year;
    struct TALER_Amount receipts_to_date;
    uint32_t current_year;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_auto_from_type ("charity_pub",
                                            &charity_pub),
      GNUNET_PQ_result_spec_uint64 ("charity_id",
                                    &charity_id),
      GNUNET_PQ_result_spec_string ("charity_name",
                                    &charity_name),
      TALER_PQ_RESULT_SPEC_AMOUNT ("max_per_year",
                                   &max_per_year),
      GNUNET_PQ_result_spec_uint32 ("current_year",
                                    &current_year),
      TALER_PQ_RESULT_SPEC_AMOUNT ("receipts_to_date",
                                   &receipts_to_date),
      GNUNET_PQ_result_spec_end
    };
    enum GNUNET_GenericReturnValue ret;

    if (GNUNET_OK !=
        GNUNET_PQ_extract_result (result,
                                  rs,
                                  i))
    {
      GNUNET_break (0);
      ctx->qs = GNUNET_DB_STATUS_HARD_ERROR;
      return;
    }
    if (current_year !=
        GNUNET_TIME_get_current_year ())
      GNUNET_assert (GNUNET_OK ==
                     TALER_amount_set_zero (max_per_year.currency,
                                            &receipts_to_date));
    ctx->qs = i + 1;
    ret = ctx->cb (ctx->cb_cls,
                   charity_id,
                   &charity_pub,
                   charity_name,
                   &max_per_year,
                   current_year,
                   &receipts_to_date);
    GNUNET_PQ_cleanup_result (rs);
    if (GNUNET_OK != ret)
      break;
  }
}


enum GNUNET_DB_QueryStatus
DH_PG_get_charities (void *cls,
                     DONAUDB_GetCharitiesCallback cb,
                     void *cb_cls)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_end
  };
  struct GetCharitiesContext ctx = {
    .cb = cb,
    .cb_cls = cb_cls,
    .pg = pg
  };
  enum GNUNET_DB_QueryStatus qs;

  PREPARE (pg,
           "get_charities",
           "SELECT"
           " charity_id"
           ",charity_pub"
           ",charity_name"
           ",max_per_year"
           ",receipts_to_date"
           ",current_year"
           " FROM charities");
  qs = GNUNET_PQ_eval_prepared_multi_select (pg->conn,
                                             "get_charities",
                                             params,
                                             &get_charities_cb,
                                             &ctx);
  if (qs <= 0)
    return qs;
  return ctx.qs;
}
