/*
   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_info_get_token.c
 * @brief Implementation of the info_get_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_info_get_token.h"
#include "pg_helper.h"


enum GNUNET_DB_QueryStatus
CH_PG_info_get_token (
  void *cls,
  const struct CHALLENGER_AccessTokenP *token,
  uint64_t *rowid,
  json_t **address,
  struct GNUNET_TIME_Timestamp *address_expiration)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_TIME_Absolute now
    = GNUNET_TIME_absolute_get ();
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (token),
    GNUNET_PQ_query_param_absolute_time (&now),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_TIME_Absolute at;
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_uint64 ("rowid",
                                  rowid),
    TALER_PQ_result_spec_json ("address",
                               address),
    GNUNET_PQ_result_spec_absolute_time ("address_expiration_time",
                                         &at),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  PREPARE (pg,
           "info_get_token",
           "SELECT "
           "  grant_serial_id AS rowid"
           " ,address"
           " ,address_expiration_time"
           " FROM tokens"
           " WHERE access_token=$1"
           "   AND token_expiration_time > $2");
  qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                 "info_get_token",
                                                 params,
                                                 rs);
  if (qs > 0)
    *address_expiration = GNUNET_TIME_absolute_to_timestamp (at);
  return qs;
}
