/*
  This file is part of Anastasis
  Copyright (C) 2020-2022 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/get_exists_challenge_code_satisfied.c
 * @brief Anastasis database: get exists challenge code satisfied
 * @author Christian Grothoff
 */
#include "platform.h"
#include "anastasis-db_pg.h"
#include "anastasis/anastasis-database/get_exists_challenge_code_satisfied.h"
#include "anastasis/anastasis-database/transaction.h"
#include "anastasis/anastasis-database/preflight.h"
#include <taler/taler_pq_lib.h>


/**
 * Check if the 'satisfied' bit for the given challenge and code is
 * 'true' and the challenge code is not yet expired.
 *
 * @param truth_uuid identification of the challenge which the code corresponds to
 * @param code code which is now satisfied
 * @return transaction status,
 *        #GNUNET_DB_STATUS_SUCCESS_NO_RESULTS if the challenge code is not satisfied or expired
 *        #GNUNET_DB_STATUS_SUCCESS_ONE_RESULT if the challenge code has been marked as satisfied
 */
enum GNUNET_DB_QueryStatus
ANASTASIS_DB_get_exists_challenge_code_satisfied (
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid,
  const uint64_t code,
  struct GNUNET_TIME_Timestamp after)
{
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (truth_uuid),
    GNUNET_PQ_query_param_uint64 (&code),
    GNUNET_PQ_query_param_timestamp (&after),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_end
  };

  PREPARE ("get_exists_challenge_code_satisfied",
           "SELECT 1 FROM anastasis_challengecode"
           " WHERE truth_uuid=$1"
           "   AND satisfied=TRUE"
           "   AND code=$2"
           "   AND creation_date >= $3"
           " LIMIT 1;");
  return GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                   "get_exists_challenge_code_satisfied",
                                                   params,
                                                   rs);
}


/* end of get_exists_challenge_code_satisfied.c */
