/*
   This file is part of Challenger
   Copyright (C) 2023 Taler Systems SA

   Challenger 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.

   Challenger 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
   Challenger; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */
/**
 * @file src/challengerdb/do_challenge_address.c
 * @brief Implementation of the do_challenge_address 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 "do_challenge_address.h"
#include "pg_helper.h"


enum GNUNET_DB_QueryStatus
CHALLENGERDB_do_challenge_address (
  struct CHALLENGERDB_PostgresContext *ctx,
  const struct CHALLENGER_ValidationNonceP *nonce,
  const json_t *address,
  struct GNUNET_TIME_Relative retransmission_frequency,
  uint32_t *tan,
  char **state,
  struct GNUNET_TIME_Absolute *last_tx_time,
  uint32_t *auth_attempts_left,
  uint32_t *pin_transmissions_left,
  bool *pin_transmit,
  char **client_redirect_uri,
  bool *address_refused,
  bool *solved)
{
  struct GNUNET_TIME_Absolute now
    = GNUNET_TIME_absolute_get ();
  /* We must gate retransmission on
       last_tx_time + retransmission_frequency <= now
     but 'last_tx_time' is only read (under FOR UPDATE) inside the stored
     procedure, so we cannot form that sum here.  We therefore pass the
     equivalent, inverted form: the *newest* 'last_tx_time' for which a
     retransmission is still due.  The SQL then merely checks
       last_tx_time <= retransmit_cutoff.
     Note that this is deliberately a subtraction from 'now', not
     'now + retransmission_frequency': the value is compared against a
     timestamp in the *past*.  GNUNET_TIME_absolute_subtract() saturates at
     zero rather than underflowing, so a FOREVER frequency degrades to
     "never *re*transmit" (the initial PIN, sent when last_tx_time is still 0,
     is unaffected). */
  struct GNUNET_TIME_Absolute retransmit_cutoff
    = GNUNET_TIME_absolute_subtract (now,
                                     retransmission_frequency);
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (nonce),
    TALER_PQ_query_param_json (address),
    GNUNET_PQ_query_param_absolute_time (&retransmit_cutoff),
    GNUNET_PQ_query_param_absolute_time (&now),
    GNUNET_PQ_query_param_uint32 (tan),
    GNUNET_PQ_query_param_end
  };
  bool not_found;
  bool no_last_tan;
  uint32_t tan_out;
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_bool ("not_found",
                                &not_found),
    GNUNET_PQ_result_spec_absolute_time ("last_tx_time",
                                         last_tx_time),
    GNUNET_PQ_result_spec_allow_null (
      GNUNET_PQ_result_spec_uint32 ("last_pin",
                                    &tan_out),
      &no_last_tan),
    GNUNET_PQ_result_spec_bool ("pin_transmit",
                                pin_transmit),
    GNUNET_PQ_result_spec_uint32 ("auth_attempts_left",
                                  auth_attempts_left),
    GNUNET_PQ_result_spec_uint32 ("pin_transmissions_left",
                                  pin_transmissions_left),
    GNUNET_PQ_result_spec_allow_null (
      GNUNET_PQ_result_spec_string ("client_redirect_uri",
                                    client_redirect_uri),
      NULL),
    GNUNET_PQ_result_spec_allow_null (
      GNUNET_PQ_result_spec_string ("state",
                                    state),
      NULL),
    GNUNET_PQ_result_spec_bool ("address_refused",
                                address_refused),
    GNUNET_PQ_result_spec_bool ("solved",
                                solved),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  *client_redirect_uri = NULL;
  no_last_tan = true;
  PREPARE (ctx,
           "do_challenge_address",
           "SELECT "
           " out_not_found AS not_found"
           ",out_last_tx_time AS last_tx_time"
           ",out_pin_transmit AS pin_transmit"
           ",out_last_pin AS last_pin"
           ",out_state AS state"
           ",out_auth_attempts_left AS auth_attempts_left"
           ",out_pin_transmissions_left AS pin_transmissions_left"
           ",out_client_redirect_uri AS client_redirect_uri"
           ",out_address_refused AS address_refused"
           ",out_solved AS solved"
           " FROM challenger_do_challenge_set_address_and_pin"
           " ($1,$2,$3,$4,$5);");
  qs = GNUNET_PQ_eval_prepared_singleton_select (ctx->conn,
                                                 "do_challenge_address",
                                                 params,
                                                 rs);
  if (qs <= 0)
    return qs;
  if (not_found)
    return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
  if (! no_last_tan)
    *tan = tan_out;
  return qs;
}


enum GNUNET_DB_QueryStatus
CHALLENGERDB_do_challenge_address_confirm_pin (
  struct CHALLENGERDB_PostgresContext *ctx,
  const struct CHALLENGER_ValidationNonceP *nonce,
  uint32_t *auth_attempts_left)
{
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (nonce),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_uint32 ("auth_attempts_left",
                                  auth_attempts_left),
    GNUNET_PQ_result_spec_end
  };

  PREPARE (ctx,
           "do_challenge_address_confirm_pin",
           "UPDATE validations SET"
           "  last_pin=pending_pin"
           " ,pending_pin=NULL"
           " ,auth_attempts_left=3"
           " WHERE nonce=$1"
           /* nothing to promote if we did not just transmit a PIN */
           "   AND pending_pin IS NOT NULL"
           /* never resurrect an already solved validation */
           "   AND auth_attempts_left >= 0"
           " RETURNING auth_attempts_left;");
  return GNUNET_PQ_eval_prepared_singleton_select (
    ctx->conn,
    "do_challenge_address_confirm_pin",
    params,
    rs);
}
