/*
   This file is part of TALER
   Copyright (C) 2023 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 src/donaudb/insert_history_entry.c
 * @brief Implementation of the insert_history_entry 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 "insert_history_entry.h"
#include "helper.h"

enum GNUNET_DB_QueryStatus
DONAUDB_insert_history_entry (struct DONAUDB_PostgresContext *ctx,
                              const uint64_t charity_id,
                              const struct TALER_Amount *final_amount,
                              const uint64_t donation_year)
{
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_uint64 (&charity_id),
    TALER_PQ_query_param_amount (ctx->conn,
                                 final_amount),
    GNUNET_PQ_query_param_uint64 (&donation_year),
    GNUNET_PQ_query_param_end
  };
  uint64_t out_charity_id;
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_uint64 ("charity_id",
                                  &out_charity_id),
    GNUNET_PQ_result_spec_end
  };

  /* The RETURNING clause is what makes "written" distinguishable from
     "a row for this (charity,year) already exists": without it, the
     unique violation would be mapped to SUCCESS_NO_RESULTS, which is
     also what a caller checking only for `qs < 0' reads as success. */
  PREPARE (ctx,
           "insert_history_entry",
           "INSERT INTO history "
           "(charity_id"
           ",final_amount"
           ",donation_year"
           ") VALUES "
           "($1, $2, $3)"
           " ON CONFLICT (charity_id, donation_year) DO NOTHING"
           " RETURNING charity_id;");
  return GNUNET_PQ_eval_prepared_singleton_select (ctx->conn,
                                                   "insert_history_entry",
                                                   params,
                                                   rs);
}
