/*
   This file is part of TALER
   Copyright (C) 2024 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_lookup_spent_tokens_by_order.c
 * @brief Implementation of the lookup_spent_tokens_by_order function for Postgres
 * @author Christian Blättler
 */
#include "platform.h"
#include <taler/taler_error_codes.h>
#include <taler/taler_dbevents.h>
#include <taler/taler_pq_lib.h>
#include "pg_lookup_spent_tokens_by_order.h"
#include "pg_helper.h"
#include "taler_merchantdb_plugin.h"

/**
 * Closure for lookup_spent_tokens_by_order_cb().
 */
struct LookupSpentTokensByOrderContext
{

  /**
   * Plugin context.
   */
  struct PostgresClosure *pg;

  /**
   * Function to call with all results.
   */
  TALER_MERCHANTDB_UsedTokensCallback cb;

  /**
   * Closure for @e cb.
   */
  void *cb_cls;

  /**
   * Set to the query result.
   */
  enum GNUNET_DB_QueryStatus qs;
};


/**
 * Function to be called with the results of a SELECT statement
 * that has returned @a num_results results.
 *
 * @param cls of type `struct LookupSpentTokensByOrderContext *`
 * @param result the postgres result
 * @param num_results the number of results in @a result
 */
static void
lookup_spent_tokens_by_order_cb (void *cls,
                                 PGresult *result,
                                 unsigned int num_results)
{
  struct LookupSpentTokensByOrderContext *ctx = cls;

  for (unsigned int i = 0; i<num_results; i++)
  {
    uint64_t spent_token_serial;
    struct TALER_PrivateContractHashP h_contract_terms;
    struct TALER_TokenIssuePublicKeyHashP h_issue_pub;
    struct TALER_TokenUsePublicKeyP use_pub;
    struct TALER_TokenUseSignatureP use_sig;
    struct TALER_TokenIssueSignature issue_sig;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_uint64 ("spent_token_serial",
                                    &spent_token_serial),
      GNUNET_PQ_result_spec_auto_from_type ("h_contract_terms",
                                            &h_contract_terms),
      GNUNET_PQ_result_spec_auto_from_type ("h_pub",
                                            &h_issue_pub),
      GNUNET_PQ_result_spec_auto_from_type ("token_pub",
                                            &use_pub),
      GNUNET_PQ_result_spec_auto_from_type ("token_sig",
                                            &use_sig),
      GNUNET_PQ_result_spec_unblinded_sig ("blind_sig",
                                           &issue_sig.signature),
      GNUNET_PQ_result_spec_end
    };

    if (GNUNET_OK !=
        GNUNET_PQ_extract_result (result,
                                  rs,
                                  i))
    {
      GNUNET_break (0);
      ctx->qs = GNUNET_DB_STATUS_HARD_ERROR;
      return;
    }
    ctx->cb (ctx->cb_cls,
             spent_token_serial,
             &h_contract_terms,
             &h_issue_pub,
             &use_pub,
             &use_sig,
             &issue_sig);
    GNUNET_PQ_cleanup_result (rs);
  }
  ctx->qs = num_results;
}


enum GNUNET_DB_QueryStatus
TMH_PG_lookup_spent_tokens_by_order (void *cls,
                                     uint64_t order_serial,
                                     TALER_MERCHANTDB_UsedTokensCallback cb,
                                     void *cb_cls)
{
  struct PostgresClosure *pg = cls;
  struct LookupSpentTokensByOrderContext ctx = {
    .pg = pg,
    .cb = cb,
    .cb_cls = cb_cls
  };
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_uint64 (&order_serial),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  PREPARE (pg,
           "lookup_spent_tokens_by_order",
           "SELECT"
           " spent_token_serial"
           ",h_contract_terms"
           ",h_pub"
           ",token_pub"
           ",token_sig"
           ",blind_sig"
           " FROM merchant_used_tokens"
           " JOIN merchant_contract_terms"
           "   USING (h_contract_terms)"
           " JOIN merchant_token_family_keys"
           "   USING (token_family_key_serial)"
           " WHERE order_serial=$1");

  qs = GNUNET_PQ_eval_prepared_multi_select (pg->conn,
                                             "lookup_spent_tokens_by_order",
                                             params,
                                             &lookup_spent_tokens_by_order_cb,
                                             &ctx);

  if (qs < 0)
    return qs;
  return ctx.qs;
}
