/*
   This file is part of TALER
   Copyright (C) 2022, 2023, 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 backenddb/pg_insert_deposit_confirmation.c
 * @brief Implementation of the insert_deposit_confirmation 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_insert_deposit_confirmation.h"
#include "pg_helper.h"


enum GNUNET_DB_QueryStatus
TMH_PG_insert_deposit_confirmation (
  void *cls,
  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_DB_EventHeaderP es = {
    .size = htons (sizeof (es)),
    .type = htons (TALER_DBEVENT_MERCHANT_NEW_WIRE_DEADLINE)
  };
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_string (instance_id),
    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), /* 7 */
    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_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_uint64 ("deposit_confirmation_serial",
                                  deposit_confirmation_serial_id),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  /* 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));
  check_connection (pg);
  PREPARE (pg,
           "insert_deposit_confirmation",
           "WITH md AS"
           "  (SELECT account_serial, merchant_serial"
           "   FROM merchant_accounts"
           "   WHERE h_wire=$7"
           "    AND merchant_serial="
           "     (SELECT merchant_serial"
           "        FROM merchant_instances"
           "        WHERE merchant_id=$1))"
           ", ed AS"
           "  (SELECT signkey_serial"
           "   FROM merchant_exchange_signing_keys"
           "   WHERE exchange_pub=$9"
           "   ORDER BY start_date DESC"
           "   LIMIT 1)"
           "INSERT INTO merchant_deposit_confirmations"
           "(order_serial"
           ",deposit_timestamp"
           ",exchange_url"
           ",total_without_fee"
           ",wire_fee"
           ",exchange_sig"
           ",wire_transfer_deadline"
           ",signkey_serial"
           ",account_serial)"
           " SELECT "
           "   order_serial"
           "  ,$3, $4, $5, $6, $8, $10"
           "  ,ed.signkey_serial"
           "  ,md.account_serial"
           "  FROM merchant_contract_terms"
           "   JOIN md USING (merchant_serial)"
           "   FULL OUTER JOIN ed ON TRUE"
           "  WHERE h_contract_terms=$2"
           " RETURNING deposit_confirmation_serial");
  qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                 "insert_deposit_confirmation",
                                                 params,
                                                 rs);
  if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT == qs)
  {
    /* inform taler-merchant-depositcheck about new deadline */
    struct GNUNET_TIME_AbsoluteNBO nbo;

    nbo = GNUNET_TIME_absolute_hton (wire_transfer_deadline.abs_time);
    GNUNET_PQ_event_notify (pg->conn,
                            &es,
                            &nbo,
                            sizeof (nbo));
  }
  return qs;
}
