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


enum GNUNET_DB_QueryStatus
TMH_PG_finalize_transfer_status (
  void *cls,
  const char *exchange_url,
  const struct TALER_WireTransferIdentifierRawP *wtid,
  const struct GNUNET_HashCode *h_details,
  const struct TALER_Amount *total_amount,
  const struct TALER_Amount *wire_fee,
  const struct TALER_ExchangePublicKeyP *exchange_pub,
  const struct TALER_ExchangeSignatureP *exchange_sig)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (wtid),
    GNUNET_PQ_query_param_string (exchange_url),
    TALER_PQ_query_param_amount_with_currency (pg->conn,
                                               total_amount),
    TALER_PQ_query_param_amount_with_currency (pg->conn,
                                               wire_fee),
    GNUNET_PQ_query_param_auto_from_type (h_details),
    GNUNET_PQ_query_param_auto_from_type (exchange_pub),
    GNUNET_PQ_query_param_auto_from_type (exchange_sig),
    GNUNET_PQ_query_param_end
  };

  check_connection (pg);
  PREPARE (pg,
           "finalize_transfer_status",
           "WITH subquery AS ("
           "  SELECT signkey_serial"
           "    FROM merchant_exchange_signing_keys"
           "   WHERE exchange_pub=$6"
           ")"
           "UPDATE merchant_expected_transfers SET"
           " last_http_status=200"
           ",last_ec=0"
           ",last_detail=NULL"
           ",retry_needed=FALSE"
           ",retry_time=0"
           ",expected_credit_amount=$3"
           ",wire_fee=$4"
           ",h_details=$5"
           ",signkey_serial=subquery.signkey_serial"
           ",exchange_sig=$7"
           " FROM subquery"
           " WHERE wtid=$1"
           "   AND exchange_url=$2");
  return GNUNET_PQ_eval_prepared_non_select (
    pg->conn,
    "finalize_transfer_status",
    params);
}
