/*
   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 challengerdb/pg_token_add_token.c
 * @brief Implementation of the token_add_token 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_token_add_token.h"
#include "pg_helper.h"


enum GNUNET_DB_QueryStatus
CH_PG_token_add_token (
  void *cls,
  const struct CHALLENGER_ValidationNonceP *nonce,
  const struct CHALLENGER_AccessTokenP *token,
  struct GNUNET_TIME_Relative token_expiration,
  struct GNUNET_TIME_Relative address_expiration)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_TIME_Absolute ge
    = GNUNET_TIME_relative_to_absolute (token_expiration);
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (nonce),
    GNUNET_PQ_query_param_auto_from_type (token),
    GNUNET_PQ_query_param_absolute_time (&ge),
    GNUNET_PQ_query_param_relative_time (&address_expiration),
    GNUNET_PQ_query_param_end
  };

  PREPARE (pg,
           "token_add_token",
           "INSERT INTO tokens"
           " (access_token"
           " ,address"
           " ,token_expiration_time"
           " ,address_expiration_time"
           ") SELECT"
           " $2, address, $3, $4 + last_tx_time"
           " FROM validations"
           " WHERE nonce=$1;");
  return GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                             "token_add_token",
                                             params);
}
