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


enum GNUNET_DB_QueryStatus
TMH_PG_solve_mfa_challenge (
  void *cls,
  uint64_t challenge_id,
  const struct TALER_MERCHANT_MFA_BodyHash *h_body,
  const char *solution,
  bool *solved,
  uint32_t *retry_counter)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
  bool no_match;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_uint64 (&challenge_id),
    GNUNET_PQ_query_param_auto_from_type (h_body),
    GNUNET_PQ_query_param_string (solution),
    GNUNET_PQ_query_param_absolute_time (&now),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_bool ("out_solved",
                                solved),
    GNUNET_PQ_result_spec_allow_null (
      GNUNET_PQ_result_spec_uint32 ("out_retry_counter",
                                    retry_counter),
      &no_match),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  /* conservatively set security-relevant return values to
     safe values, even though these should not be used with qs <= 0 */
  *solved = false;
  *retry_counter = 0;
  PREPARE (pg,
           "solve_mfa_challenge",
           "SELECT"
           "  out_solved"
           " ,out_retry_counter"
           "  FROM merchant_do_solve_mfa_challenge"
           " ($1, $2, $3, $4);");
  qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                 "solve_mfa_challenge",
                                                 params,
                                                 rs);
  if (qs <= 0)
    return qs;
  if (no_match)
  {
    GNUNET_PQ_cleanup_result (rs);
    return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
  }
  GNUNET_PQ_cleanup_result (rs);
  return qs;
}
