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


enum GNUNET_DB_QueryStatus
TMH_PG_increment_money_pots (
  void *cls,
  const char *instance_id,
  size_t money_pots_len,
  const uint64_t *money_pot_ids,
  const struct TALER_Amount *pot_increments)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_string (instance_id),
    GNUNET_PQ_query_param_array_uint64 (money_pots_len,
                                        money_pot_ids,
                                        pg->conn),
    TALER_PQ_query_param_array_amount_with_currency (money_pots_len,
                                                     pot_increments,
                                                     pg->conn),
    GNUNET_PQ_query_param_end
  };
  bool not_found;
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_bool ("not_found",
                                &not_found),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  PREPARE (pg,
           "increment_money_pots",
           "SELECT"
           " out_not_found AS not_found"
           " FROM merchant_do_increment_money_pots"
           "($1,$2,$3);");
  qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                 "increment_money_pots",
                                                 params,
                                                 rs);
  GNUNET_PQ_cleanup_query_params_closures (params);
  if (qs <= 0)
    return qs;
  if (not_found)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "Some money pots could not be implemented because they no longer exist. This is not a bug and expected to happen if a merchant deletes money pots that were used in orders active at the time.\n");
  }
  return GNUNET_DB_STATUS_SUCCESS_ONE_RESULT;
}
