/*
  This file is part of Anastasis
  Copyright (C) 2026 Anastasis SARL

  Anastasis is free software; you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free Software
  Foundation; either version 3, or (at your option) any later version.

  Anastasis 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 Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License along with
  Anastasis; see the file COPYING.GPL.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file stasis/update_totp_counter.c
 * @brief Anastasis database: accept a TOTP time step counter once
 * @author Christian Grothoff
 */
#include "platform.h"
#include "anastasis-db_pg.h"
#include "anastasis/anastasis-database/update_totp_counter.h"
#include "anastasis/anastasis-database/transaction.h"
#include "anastasis/anastasis-database/preflight.h"
#include <taler/taler_pq_lib.h>


/**
 * Consume the TOTP time step @a counter for @a truth_uuid.
 *
 * The comparison and the store are one statement on purpose: the row lock
 * taken by the UPDATE is what keeps two requests that carry the same code from
 * both being told they won.
 *
 * @param truth_uuid identification of the challenge the code belongs to
 * @param counter time step counter the code was computed for
 * @return transaction status
 */
enum GNUNET_DB_QueryStatus
ANASTASIS_DB_update_totp_counter (
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid,
  uint64_t counter)
{
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (truth_uuid),
    GNUNET_PQ_query_param_uint64 (&counter),
    GNUNET_PQ_query_param_end
  };

  PREPARE ("update_totp_counter",
           "UPDATE anastasis_truth"
           " SET last_totp_counter=$2"
           " WHERE truth_uuid=$1"
           "   AND last_totp_counter < $2;");
  return GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                             "update_totp_counter",
                                             params);
}


/* end of update_totp_counter.c */
