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


enum TALER_MERCHANTDB_DepositConfirmationStatus
TALER_MERCHANTDB_insert_deposit_confirmation (
  struct TALER_MERCHANTDB_PostgresContext *pg,
  const char *instance_id,
  struct GNUNET_TIME_Timestamp deposit_timestamp,
  const struct TALER_PrivateContractHashP *h_contract_terms,
  const char *exchange_url,
  struct GNUNET_TIME_Timestamp wire_transfer_deadline,
  const struct TALER_Amount *total_without_fees,
  const struct TALER_Amount *wire_fee,
  const struct TALER_MerchantWireHashP *h_wire,
  const struct TALER_ExchangeSignatureP *exchange_sig,
  const struct TALER_ExchangePublicKeyP *exchange_pub,
  uint64_t *deposit_confirmation_serial_id)
{
  struct GNUNET_TIME_AbsoluteNBO nbo
    = GNUNET_TIME_absolute_hton (wire_transfer_deadline.abs_time);
  char *nbo_str
    = GNUNET_STRINGS_data_to_string_alloc (&nbo,
                                           sizeof (nbo));
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (h_contract_terms),
    GNUNET_PQ_query_param_timestamp (&deposit_timestamp),
    GNUNET_PQ_query_param_string (exchange_url),
    TALER_PQ_query_param_amount_with_currency (pg->conn,
                                               total_without_fees),
    TALER_PQ_query_param_amount_with_currency (pg->conn,
                                               wire_fee),
    GNUNET_PQ_query_param_auto_from_type (h_wire), /* 6 */
    GNUNET_PQ_query_param_auto_from_type (exchange_sig),
    GNUNET_PQ_query_param_auto_from_type (exchange_pub),
    GNUNET_PQ_query_param_timestamp (&wire_transfer_deadline),
    GNUNET_PQ_query_param_string (nbo_str),
    GNUNET_PQ_query_param_end
  };
  bool no_order;
  bool no_account;
  bool no_signkey;
  bool conflict;
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_bool ("no_order",
                                &no_order),
    GNUNET_PQ_result_spec_bool ("no_account",
                                &no_account),
    GNUNET_PQ_result_spec_bool ("no_signkey",
                                &no_signkey),
    GNUNET_PQ_result_spec_bool ("conflict",
                                &conflict),
    GNUNET_PQ_result_spec_uint64 ("deposit_confirmation_serial",
                                  deposit_confirmation_serial_id),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  GNUNET_assert (NULL != pg->current_merchant_id);
  GNUNET_assert (0 == strcmp (instance_id,
                              pg->current_merchant_id));
  /* no preflight check here, run in transaction by caller! */
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Storing deposit confirmation for instance `%s' h_contract_terms `%s', total_without_fees: %s and wire transfer deadline in %s\n",
              instance_id,
              GNUNET_h2s (&h_contract_terms->hash),
              TALER_amount2s (total_without_fees),
              GNUNET_TIME_relative2s (
                GNUNET_TIME_absolute_get_remaining (
                  wire_transfer_deadline.abs_time),
                true));
  TMH_PQ_prepare_anon (pg,
                       "SELECT "
                       "  out_no_account AS no_account"
                       " ,out_no_order AS no_order"
                       " ,out_no_signkey AS no_signkey"
                       " ,out_conflict AS conflict"
                       " ,out_deposit_confirmation_serial AS deposit_confirmation_serial"
                       " FROM merchant_do_insert_deposit_confirmation"
                       "  ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10);");
  qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                 "",
                                                 params,
                                                 rs);
  GNUNET_free (nbo_str);
  switch (qs)
  {
  case GNUNET_DB_STATUS_HARD_ERROR:
    return TALER_MERCHANTDB_DCS_HARD_ERROR;
  case GNUNET_DB_STATUS_SOFT_ERROR:
    return TALER_MERCHANTDB_DCS_SOFT_ERROR;
  case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
    /* stored procedure always returns exactly one row */
    GNUNET_break (0);
    return TALER_MERCHANTDB_DCS_NO_RESULTS;
  case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
    break;
  }
  /* Checked in the same order as the stored procedure evaluates them. */
  if (no_account)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Merchant account `%s' unknown, cannot store deposit confirmation for contract `%s'\n",
                TALER_B2S (h_wire),
                GNUNET_h2s (&h_contract_terms->hash));
    return TALER_MERCHANTDB_DCS_NO_ACCOUNT;
  }
  if (no_signkey)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Exchange signing key `%s' of `%s' unknown, cannot store deposit confirmation for contract `%s'\n",
                TALER_B2S (exchange_pub),
                exchange_url,
                GNUNET_h2s (&h_contract_terms->hash));
    return TALER_MERCHANTDB_DCS_NO_SIGNKEY;
  }
  if (no_order)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Order for contract `%s' unknown, cannot store deposit confirmation\n",
                GNUNET_h2s (&h_contract_terms->hash));
    return TALER_MERCHANTDB_DCS_NO_ORDER;
  }
  if (conflict)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Conflicting deposit confirmation already stored for contract `%s' at `%s'\n",
                GNUNET_h2s (&h_contract_terms->hash),
                exchange_url);
    return TALER_MERCHANTDB_DCS_CONFLICT;
  }
  GNUNET_assert (0 != *deposit_confirmation_serial_id);
  return TALER_MERCHANTDB_DCS_SUCCESS;
}
