/*
   This file is part of TALER
   Copyright (C) 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_spent_token.c
 * @brief Implementation of the insert_spent_token function for Postgres
 * @author Christian Blättler
 */
#include "platform.h"
#include <taler/taler_error_codes.h>
#include <taler/taler_dbevents.h>
#include <taler/taler_pq_lib.h>
#include "pg_insert_spent_token.h"
#include "pg_helper.h"


enum GNUNET_DB_QueryStatus
TMH_PG_insert_spent_token (
  void *cls,
  const struct TALER_PrivateContractHashP *h_contract_terms,
  const struct TALER_TokenIssuePublicKeyHashP *h_issue_pub,
  const struct TALER_TokenUsePublicKeyP *use_pub,
  const struct TALER_TokenUseSignatureP *use_sig,
  const struct TALER_TokenIssueSignature *issue_sig)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (h_contract_terms),
    GNUNET_PQ_query_param_auto_from_type (h_issue_pub),
    GNUNET_PQ_query_param_auto_from_type (use_pub),
    GNUNET_PQ_query_param_auto_from_type (use_sig),
    GNUNET_PQ_query_param_unblinded_sig (issue_sig->signature),
    GNUNET_PQ_query_param_end
  };
  bool no_fam;
  bool conflict; /* used to signal double-spending */
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_bool ("out_no_family",
                                &no_fam),
    GNUNET_PQ_result_spec_bool ("out_conflict",
                                &conflict),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Storing token spent with key %s\n",
              GNUNET_h2s (&h_issue_pub->hash));
  PREPARE (pg,
           "spent_token_insert",
           "SELECT"
           "  out_no_family"
           " ,out_conflict"
           "  FROM merchant_do_insert_spent_token"
           "($1, $2, $3, $4, $5);");
  qs = GNUNET_PQ_eval_prepared_singleton_select (
    pg->conn,
    "spent_token_insert",
    params,
    rs);
  if (qs < 0)
    return qs;
  if (no_fam)
  {
    GNUNET_break (0);
    return GNUNET_DB_STATUS_HARD_ERROR;
  }
  if (conflict)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Client attempted to double-spend token\n");
    return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
  }
  return qs;
}
