/*
   This file is part of TALER
   Copyright (C) 2026 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 src/exchangedb/iterate_legitimization_outcomes_above_serial_id.c
 * @brief Implementation of the iterate_legitimization_outcomes_above_serial_id function for Postgres
 * @author Christian Grothoff
 */
#include "taler/taler_pq_lib.h"
#include "helper.h"
#include "exchange-database/iterate_legitimization_outcomes_above_serial_id.h"


/**
 * Closure for #legitimization_outcome_cb().
 */
struct LegitimizationOutcomeContext
{
  /**
   * Function to call for each outcome.
   */
  TALER_EXCHANGEDB_LegitimizationOutcomeCallback cb;

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

  /**
   * Query status to return.
   */
  enum GNUNET_DB_QueryStatus qs;
};


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

  for (unsigned int i = 0; i < num_results; i++)
  {
    uint64_t rowid;
    struct TALER_NormalizedPaytoHashP h_payto;
    struct GNUNET_TIME_Timestamp decision_time;
    struct GNUNET_TIME_Timestamp expiration_time;
    bool has_aml_decision;
    bool has_legitimization_process;
    bool has_expired_predecessor;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_uint64 ("outcome_serial_id",
                                    &rowid),
      GNUNET_PQ_result_spec_auto_from_type ("h_payto",
                                            &h_payto),
      GNUNET_PQ_result_spec_timestamp ("decision_time",
                                       &decision_time),
      GNUNET_PQ_result_spec_timestamp ("expiration_time",
                                       &expiration_time),
      GNUNET_PQ_result_spec_bool ("has_aml_decision",
                                  &has_aml_decision),
      GNUNET_PQ_result_spec_bool ("has_legitimization_process",
                                  &has_legitimization_process),
      GNUNET_PQ_result_spec_bool ("has_expired_predecessor",
                                  &has_expired_predecessor),
      GNUNET_PQ_result_spec_end
    };
    enum GNUNET_GenericReturnValue rval;

    if (GNUNET_OK !=
        GNUNET_PQ_extract_result (result,
                                  rs,
                                  i))
    {
      GNUNET_break (0);
      loc->qs = GNUNET_DB_STATUS_HARD_ERROR;
      return;
    }
    loc->qs = i + 1;
    rval = loc->cb (loc->cb_cls,
                    rowid,
                    &h_payto,
                    decision_time,
                    expiration_time,
                    has_aml_decision,
                    has_legitimization_process,
                    has_expired_predecessor);
    GNUNET_PQ_cleanup_result (rs);
    if (GNUNET_OK != rval)
      break;
  }
}


enum GNUNET_DB_QueryStatus
TALER_EXCHANGEDB_iterate_legitimization_outcomes_above_serial_id (
  struct TALER_EXCHANGEDB_PostgresContext *pg,
  uint64_t serial_id,
  TALER_EXCHANGEDB_LegitimizationOutcomeCallback cb,
  TALER_EXCHANGEDB_LEGITIMIZATION_OUTCOME_RESULT_CLOSURE *cb_cls)
{
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_uint64 (&serial_id),
    GNUNET_PQ_query_param_end
  };
  struct LegitimizationOutcomeContext loc = {
    .cb = cb,
    .cb_cls = cb_cls
  };
  enum GNUNET_DB_QueryStatus qs;

  /* The three EXISTS clauses are the three ways the exchange's own code
     creates an outcome; the caller decides what to make of them.

     `decision_time' is a *rounded* timestamp while `start_time' is not, so a
     process started at the very moment of the decision can have a start_time
     up to a second past it.  Hence the second of slack, subtracted from
     start_time rather than added to decision_time so that a decision_time of
     "forever" does not overflow. */
  PREPARE (pg,
           "iterate_legitimization_outcomes_above_serial_id",
           "SELECT"
           " lo.outcome_serial_id"
           ",lo.h_payto"
           ",lo.decision_time"
           ",lo.expiration_time"
           ",EXISTS ("
           "   SELECT 1"
           "     FROM aml_history ah"
           "    WHERE ah.outcome_serial_id=lo.outcome_serial_id"
           " ) AS has_aml_decision"
           ",EXISTS ("
           "   SELECT 1"
           "     FROM legitimization_processes lp"
           "    WHERE lp.h_payto=lo.h_payto"
           "      AND lp.start_time-1000000<lo.decision_time"
           " ) AS has_legitimization_process"
           ",EXISTS ("
           "   SELECT 1"
           "     FROM legitimization_outcomes pre"
           "    WHERE pre.h_payto=lo.h_payto"
           "      AND pre.outcome_serial_id<lo.outcome_serial_id"
           "      AND pre.expiration_time<=lo.decision_time"
           " ) AS has_expired_predecessor"
           " FROM legitimization_outcomes lo"
           " WHERE lo.outcome_serial_id>=$1"
           " ORDER BY lo.outcome_serial_id ASC;");
  qs = GNUNET_PQ_eval_prepared_multi_select (
    pg->conn,
    "iterate_legitimization_outcomes_above_serial_id",
    params,
    &legitimization_outcome_cb,
    &loc);
  if (qs > 0)
    return loc.qs;
  GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR != qs);
  return qs;
}
