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


enum GNUNET_DB_QueryStatus
CHALLENGERDB_update_validation (
  struct CHALLENGERDB_PostgresContext *ctx,
  const struct CHALLENGER_ValidationNonceP *nonce,
  uint64_t client_id,
  const char *client_scope,
  const char *client_state,
  const char *client_redirect_uri,
  const char *code_challenge,
  uint32_t code_challenge_method,
  json_t **last_address,
  uint32_t *address_attempts_left,
  uint32_t *pin_transmissions_left,
  uint32_t *auth_attempts_left,
  bool *solved,
  struct GNUNET_TIME_Absolute *last_tx_time)
{
  struct GNUNET_TIME_Absolute now
    = GNUNET_TIME_absolute_get ();
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (nonce),
    GNUNET_PQ_query_param_uint64 (&client_id),
    NULL != client_scope
    ? GNUNET_PQ_query_param_string (client_scope)
    : GNUNET_PQ_query_param_null (),
    NULL != client_state
    ? GNUNET_PQ_query_param_string (client_state)
    : GNUNET_PQ_query_param_null (),
    NULL != client_redirect_uri
    ? GNUNET_PQ_query_param_string (client_redirect_uri)
    : GNUNET_PQ_query_param_null (),
    NULL != code_challenge
    ? GNUNET_PQ_query_param_string (code_challenge)
    : GNUNET_PQ_query_param_null (),
    GNUNET_PQ_query_param_uint32 (&code_challenge_method),
    GNUNET_PQ_query_param_absolute_time (&now),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_allow_null (
      TALER_PQ_result_spec_json ("address",
                                 last_address),
      NULL),
    GNUNET_PQ_result_spec_uint32 ("address_attempts_left",
                                  address_attempts_left),
    GNUNET_PQ_result_spec_uint32 ("pin_transmissions_left",
                                  pin_transmissions_left),
    GNUNET_PQ_result_spec_uint32 ("auth_attempts_left",
                                  auth_attempts_left),
    GNUNET_PQ_result_spec_bool ("solved",
                                solved),
    GNUNET_PQ_result_spec_absolute_time ("last_tx_time",
                                         last_tx_time),
    GNUNET_PQ_result_spec_end
  };

  *last_address = NULL;
  /* A repeated /authorize must never *weaken* an existing PKCE binding
     (RFC 7636): /authorize authenticates nobody (the client_id is a plain
     query argument) and the nonce is recoverable from an issued code, so
     replaying /authorize without a code_challenge would otherwise strip the
     binding from a validation that already had one.  Hence COALESCE, just
     like for client_redirect_uri above.  code_challenge_method must move
     with the challenge it describes: the column is NOT NULL DEFAULT 0, so
     writing it unconditionally would leave a retained challenge with the
     method of the request that tried to drop it. */
  PREPARE (ctx,
           "update_validation",
           "UPDATE validations SET"
           "  client_scope=$3"
           " ,client_state=$4"
           " ,client_redirect_uri=COALESCE($5::VARCHAR,client_redirect_uri)"
           " ,code_challenge=COALESCE($6::VARCHAR,code_challenge)"
           " ,code_challenge_method=CASE"
           "    WHEN $6::VARCHAR IS NULL"
           "    THEN code_challenge_method"
           "    ELSE $7"
           "  END"
           " WHERE nonce=$1"
           "   AND client_serial_id=$2"
           "   AND expiration_time > $8"
           "   AND ( ($5::VARCHAR=client_redirect_uri)"
           "      OR ( ($5::VARCHAR IS NULL)"
           "       AND (client_redirect_uri IS NOT NULL) ) )"
           " RETURNING"
           "   address"
           "  ,address_attempts_left"
           "  ,pin_transmissions_left"
           "  ,GREATEST(0, auth_attempts_left) AS auth_attempts_left"
           "  ,auth_attempts_left = -1 AS solved"
           "  ,last_tx_time;");
  return GNUNET_PQ_eval_prepared_singleton_select (ctx->conn,
                                                   "update_validation",
                                                   params,
                                                   rs);
}
