/*
   This file is part of TALER
   Copyright (C) 2022 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/backenddb/insert_exchange_wire_fee.c
 * @brief Implementation of the insert_exchange_wire_fee function for Postgres
 * @author Christian Grothoff
 */
#include "platform.h"
#include <taler/taler_pq_lib.h>
#include "merchant-database/insert_exchange_wire_fee.h"
#include "helper.h"


enum GNUNET_DB_QueryStatus
TALER_MERCHANTDB_insert_exchange_wire_fee (
  struct TALER_MERCHANTDB_PostgresContext *pg,
  const struct TALER_MasterPublicKeyP *master_pub,
  const struct GNUNET_HashCode *h_wire_method,
  const struct TALER_WireFeeSet *fees,
  struct GNUNET_TIME_Timestamp start_date,
  struct GNUNET_TIME_Timestamp end_date,
  const struct TALER_MasterSignatureP *master_sig)
{
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (master_pub),
    GNUNET_PQ_query_param_auto_from_type (h_wire_method),
    TALER_PQ_query_param_amount_with_currency (pg->conn,
                                               &fees->wire),
    TALER_PQ_query_param_amount_with_currency (pg->conn,
                                               &fees->closing),
    GNUNET_PQ_query_param_timestamp (&start_date),
    GNUNET_PQ_query_param_timestamp (&end_date),
    GNUNET_PQ_query_param_auto_from_type (master_sig),
    GNUNET_PQ_query_param_end
  };
  bool inserted;
  bool identical;
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_bool ("inserted",
                                &inserted),
    GNUNET_PQ_result_spec_bool ("identical",
                                &identical),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  /* no preflight check here, run in its own transaction by the caller */
  /* Note: a bare 'ON CONFLICT DO NOTHING' would silently discard a
     *changed* fee for an existing (master_pub, h_wire_method,
     start_date), leaving us computing with the stale one.  The CTE
     therefore also reports whether the row that is already there is the
     one we were asked to store; if it is not, the exchange contradicted
     a fee it signed earlier and the caller must not proceed. */
  PREPARE (pg,
           "insert_exchange_wire_fee",
           "WITH ins AS ("
           " INSERT INTO merchant.merchant_exchange_wire_fees"
           " (master_pub"
           " ,h_wire_method"
           " ,wire_fee"
           " ,closing_fee"
           " ,start_date"
           " ,end_date"
           " ,master_sig)"
           " VALUES "
           " ($1, $2, $3, $4, $5, $6, $7)"
           " ON CONFLICT (master_pub,h_wire_method,start_date)"
           "   DO NOTHING"
           " RETURNING 1)"
           "SELECT"
           " EXISTS (SELECT 1 FROM ins) AS inserted"
           ",EXISTS (SELECT 1"
           "           FROM merchant.merchant_exchange_wire_fees"
           "          WHERE master_pub=$1"
           "            AND h_wire_method=$2"
           "            AND start_date=$5"
           "            AND end_date=$6"
           "            AND wire_fee=$3"
           "            AND closing_fee=$4"
           "            AND master_sig=$7) AS identical");
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Storing wire fee for %s starting at %s of %s\n",
              TALER_B2S (master_pub),
              GNUNET_TIME_timestamp2s (start_date),
              TALER_amount2s (&fees->wire));
  qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                 "insert_exchange_wire_fee",
                                                 params,
                                                 rs);
  if (qs < 0)
    return qs;
  GNUNET_break (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT == qs);
  if (inserted)
    return GNUNET_DB_STATUS_SUCCESS_ONE_RESULT;
  if (identical)
    return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
  /* FIXME: should properly distinguish this error from
     actual database failures; change signature of function eventually! */
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "Exchange %s signed a different wire fee for the same wire method and start date %s; keeping the fee we already have on file\n",
              TALER_B2S (master_pub),
              GNUNET_TIME_timestamp2s (start_date));
  GNUNET_break (0);
  return GNUNET_DB_STATUS_HARD_ERROR;
}
