/*
  This file is part of Anastasis
  Copyright (C) 2020-2022 Anastasis SARL

  Anastasis is free software; you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free Software
  Foundation; either version 3, or (at your option) any later version.

  Anastasis 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 Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License along with
  Anastasis; see the file COPYING.GPL.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file stasis/iterate_recovery_meta_data.c
 * @brief Anastasis database: iterate recovery meta data
 * @author Christian Grothoff
 */
#include "platform.h"
#include "anastasis-db_pg.h"
#include "anastasis/anastasis-database/iterate_recovery_meta_data.h"
#include "anastasis/anastasis-database/transaction.h"
#include "anastasis/anastasis-database/preflight.h"
#include <taler/taler_pq_lib.h>


struct MetaIteratorContext
{
  /**
   * Function to call on each result.
   */
  ANASTASIS_DB_RecoveryMetaCallback cb;

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

  /**
   * Set to true on database failure.
   */
  bool db_failure;
};


/**
 * Helper function for #postgres_get_recovery_meta_data().
 * To be called with the results of a SELECT statement
 * that has returned @a num_results results.
 *
 * @param cls closure of type `struct MetaIteratorContext *`
 * @param result the postgres result
 * @param num_results the number of results in @a result
 */
static void
meta_iterator (void *cls,
               PGresult *result,
               unsigned int num_results)
{
  struct MetaIteratorContext *ctx = cls;

  for (unsigned int i = 0; i<num_results; i++)
  {
    uint32_t version;
    void *meta_data;
    size_t meta_data_size;
    struct GNUNET_TIME_Timestamp ts;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_uint32 ("version",
                                    &version),
      GNUNET_PQ_result_spec_timestamp ("creation_date",
                                       &ts),
      GNUNET_PQ_result_spec_variable_size ("recovery_meta_data",
                                           &meta_data,
                                           &meta_data_size),
      GNUNET_PQ_result_spec_end
    };
    enum GNUNET_GenericReturnValue ret;

    if (GNUNET_OK !=
        GNUNET_PQ_extract_result (result,
                                  rs,
                                  i))
    {
      GNUNET_break (0);
      ctx->db_failure = true;
      return;
    }
    ret = ctx->cb (ctx->cb_cls,
                   version,
                   ts,
                   meta_data,
                   meta_data_size);
    GNUNET_PQ_cleanup_result (rs);
    if (GNUNET_OK != ret)
      break;
  }
}


/**
 * Fetch recovery document meta data for user. Returns
 * meta data in descending order from @a max_version.
 * The size of the result set may be limited.
 *
 * @param account_pub public key of the user's account
 * @param max_version the maximum version number the user requests
 * @param cb function to call on each result
 * @param cb_cls closure for @a cb
 * @return transaction status
 */
enum GNUNET_DB_QueryStatus
ANASTASIS_DB_iterate_recovery_meta_data (
  const struct ANASTASIS_CRYPTO_AccountPublicKeyP *account_pub,
  uint32_t max_version,
  ANASTASIS_DB_RecoveryMetaCallback cb,
  void *cb_cls)
{
  struct MetaIteratorContext ctx = {
    .cb = cb,
    .cb_cls = cb_cls
  };
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (account_pub),
    GNUNET_PQ_query_param_uint32 (&max_version),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  PREPARE ("iterate_recovery_meta_data",
           "SELECT "
           " version"
           ",creation_date"
           ",recovery_meta_data"
           " FROM anastasis_recoverydocument"
           " WHERE user_id=$1"
           "   AND version < $2"
           " ORDER BY version DESC"
           " LIMIT 1000;");
  qs = GNUNET_PQ_eval_prepared_multi_select (pg->conn,
                                             "iterate_recovery_meta_data",
                                             params,
                                             &meta_iterator,
                                             &ctx);
  if (qs < 0)
    return qs;
  if (ctx.db_failure)
    return GNUNET_DB_STATUS_HARD_ERROR;
  return qs;
}


/* end of iterate_recovery_meta_data.c */
