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


enum GNUNET_DB_QueryStatus
TALER_MERCHANTDB_insert_issued_token (
  struct TALER_MERCHANTDB_PostgresContext *pg,
  const struct TALER_PrivateContractHashP *h_contract_terms,
  const struct TALER_TokenIssuePublicKeyHashP *h_issue_pub,
  const struct TALER_BlindedTokenIssueSignature *blind_sig,
  bool *no_family)
{
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (h_issue_pub),
    GNUNET_PQ_query_param_auto_from_type (h_contract_terms),
    GNUNET_PQ_query_param_blinded_sig (blind_sig->signature),
    GNUNET_PQ_query_param_end
  };
  bool no_fam = false;
  bool existed = false;
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_bool ("out_no_family",
                                &no_fam),
    GNUNET_PQ_result_spec_bool ("out_existed",
                                &existed),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  GNUNET_assert (NULL != pg->current_merchant_id);
  TMH_PQ_prepare_anon (pg,
                       "SELECT"
                       "  out_no_family"
                       " ,out_existed"
                       "  FROM merchant_do_insert_issued_token"
                       " ($1, $2, $3);");
  qs = GNUNET_PQ_eval_prepared_singleton_select (
    pg->conn,
    "",
    params,
    rs);
  *no_family = false;
  if (qs <= 0)
    return qs;
  if (no_fam)
  {
    /* The token family (key) was deleted after the order was created;
       this is a client-visible conflict, not an internal failure. */
    *no_family = true;
    return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
  }
  if (existed)
    return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
  return qs;
}
