/*
   This file is part of TALER
   Copyright (C) 2025 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/backenddb/iterate_expected_transfers.c
 * @brief Implementation of the iterate_expected_transfers function for Postgres
 * @author Christian Grothoff
 */
#include "platform.h"
#include <taler/taler_pq_lib.h>
#include "merchant-database/iterate_expected_transfers.h"
#include "helper.h"
#include <microhttpd.h> /* for HTTP status codes */


/**
 * Hard upper bound on the number of records returned by a single
 * call, regardless of the limit requested by the client.
 */
#define MAX_RECORDS 50000


/**
 * Closure for #lookup_expected_transfers_cb().
 */
struct LookupExpectedTransfersContext
{
  /**
   * Function to call on results.
   */
  TALER_MERCHANTDB_IncomingCallback cb;

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

  /**
   * Postgres context.
   */
  struct TALER_MERCHANTDB_PostgresContext *pg;

  /**
   * Transaction status (set).
   */
  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 LookupExpectedTransfersContext *`
 * @param result the postgres result
 * @param num_results the number of results in @a result
 */
static void
lookup_expected_transfers_cb (void *cls,
                              PGresult *result,
                              unsigned int num_results)
{
  struct LookupExpectedTransfersContext *ltc = cls;

  for (unsigned int i = 0; i<num_results; i++)
  {
    struct TALER_Amount expected_credit_amount;
    struct TALER_WireTransferIdentifierRawP wtid;
    struct TALER_FullPayto payto_uri;
    char *exchange_url;
    uint64_t expected_transfer_serial_id;
    struct GNUNET_TIME_Timestamp execution_time
      = GNUNET_TIME_UNIT_ZERO_TS;
    bool confirmed;
    bool validated;
    bool no_amount;
    char *last_detail = NULL;
    uint32_t last_http_status = 0;
    uint32_t last_ec = TALER_EC_NONE;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_allow_null (
        TALER_PQ_result_spec_amount_with_currency ("expected_credit_amount",
                                                   &expected_credit_amount),
        &no_amount),
      GNUNET_PQ_result_spec_auto_from_type ("wtid",
                                            &wtid),
      GNUNET_PQ_result_spec_string ("payto_uri",
                                    &payto_uri.full_payto),
      GNUNET_PQ_result_spec_string ("exchange_url",
                                    &exchange_url),
      GNUNET_PQ_result_spec_uint64 ("expected_credit_serial",
                                    &expected_transfer_serial_id),
      GNUNET_PQ_result_spec_allow_null (
        GNUNET_PQ_result_spec_timestamp ("execution_time",
                                         &execution_time),
        NULL),
      GNUNET_PQ_result_spec_bool ("confirmed",
                                  &confirmed),
      GNUNET_PQ_result_spec_allow_null (
        GNUNET_PQ_result_spec_uint32 ("last_http_status",
                                      &last_http_status),
        NULL),
      GNUNET_PQ_result_spec_allow_null (
        GNUNET_PQ_result_spec_uint32 ("last_ec",
                                      &last_ec),
        NULL),
      GNUNET_PQ_result_spec_allow_null (
        GNUNET_PQ_result_spec_string ("last_detail",
                                      &last_detail),
        NULL),
      GNUNET_PQ_result_spec_end
    };

    if (GNUNET_OK !=
        GNUNET_PQ_extract_result (result,
                                  rs,
                                  i))
    {
      GNUNET_break (0);
      ltc->qs = GNUNET_DB_STATUS_HARD_ERROR;
      return;
    }
    validated = ( (MHD_HTTP_OK == last_http_status) &&
                  (TALER_EC_NONE == last_ec) );
    ltc->cb (ltc->cb_cls,
             no_amount
             ? NULL
             : &expected_credit_amount,
             &wtid,
             payto_uri,
             exchange_url,
             expected_transfer_serial_id,
             execution_time,
             confirmed,
             validated,
             last_http_status,
             last_ec,
             last_detail);
    GNUNET_PQ_cleanup_result (rs);
  }
  ltc->qs = num_results;
}


enum GNUNET_DB_QueryStatus
TALER_MERCHANTDB_iterate_expected_transfers (
  struct TALER_MERCHANTDB_PostgresContext *pg,
  const char *instance_id,
  struct TALER_FullPayto payto_uri,
  struct GNUNET_TIME_Timestamp before,
  struct GNUNET_TIME_Timestamp after,
  int64_t limit,
  uint64_t offset,
  enum TALER_EXCHANGE_YesNoAll confirmed,
  enum TALER_EXCHANGE_YesNoAll verified,
  TALER_MERCHANTDB_IncomingCallback cb,
  void *cb_cls)
{
  uint64_t plimit = GNUNET_MIN ((uint64_t) MAX_RECORDS,
                                TALER_MERCHANTDB_abs_limit (limit));
  bool by_time = ( (! GNUNET_TIME_absolute_is_never (before.abs_time)) ||
                   (! GNUNET_TIME_absolute_is_zero (after.abs_time)) );
  struct LookupExpectedTransfersContext ltc = {
    .cb = cb,
    .cb_cls = cb_cls,
    .pg = pg
  };
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_timestamp (&before),
    GNUNET_PQ_query_param_timestamp (&after),
    GNUNET_PQ_query_param_uint64 (&offset),
    GNUNET_PQ_query_param_uint64 (&plimit),
    NULL == payto_uri.full_payto
    ? GNUNET_PQ_query_param_null () /* NULL: do not filter by payto URI */
    : GNUNET_PQ_query_param_string (payto_uri.full_payto),
    GNUNET_PQ_query_param_bool (! by_time),     /* $6: filter by time? */
    GNUNET_PQ_query_param_bool (TALER_EXCHANGE_YNA_ALL == confirmed), /* filter by confirmed? */
    GNUNET_PQ_query_param_bool (TALER_EXCHANGE_YNA_YES == confirmed),
    GNUNET_PQ_query_param_bool (TALER_EXCHANGE_YNA_ALL == verified), /* filter by verified? */
    GNUNET_PQ_query_param_bool (TALER_EXCHANGE_YNA_YES == verified),

    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  GNUNET_assert (NULL != pg->current_merchant_id);
  GNUNET_assert (0 == strcmp (instance_id,
                              pg->current_merchant_id));
  if (limit > 0)
  {
    TMH_PQ_prepare_anon (pg,
                         "SELECT"
                         " met.expected_credit_amount"
                         ",met.wtid"
                         ",mac.payto_uri"
                         ",met.exchange_url"
                         ",met.expected_credit_serial"
                         ",mts.execution_time"
                         ",met.confirmed"
                         ",met.last_http_status"
                         ",met.last_ec"
                         ",met.last_detail"
                         " FROM merchant_expected_transfers met"
                         "  JOIN merchant_accounts mac"
                         "    USING (account_serial)"
                         "  LEFT JOIN merchant_transfer_signatures mts"
                         "    USING (expected_credit_serial)"
                         " WHERE ( $6 OR "
                         "         (mts.execution_time IS NOT NULL AND"
                         "          mts.execution_time < $1 AND"
                         "          mts.execution_time >= $2) )"
                         "   AND ( (CAST($5 AS TEXT) IS NULL) OR "
                         "         (REGEXP_REPLACE(mac.payto_uri,'\\?.*','')"
                         "         =REGEXP_REPLACE($5,'\\?.*','')) )"
                         "   AND ( $7 OR "
                         "         (met.confirmed = $8) )"
                         "   AND ( $9 OR "
                         "         ($10 = (200=met.last_http_status) AND"
                         "                (0=met.last_ec) ) )"
                         "   AND (met.expected_credit_serial > $3)"
                         " ORDER BY met.expected_credit_serial ASC"
                         " LIMIT $4");
  }
  else
  {
    TMH_PQ_prepare_anon (pg,
                         "SELECT"
                         " met.expected_credit_amount"
                         ",met.wtid"
                         ",mac.payto_uri"
                         ",met.exchange_url"
                         ",met.expected_credit_serial"
                         ",mts.execution_time"
                         ",met.confirmed"
                         ",met.last_http_status"
                         ",met.last_ec"
                         ",met.last_detail"
                         " FROM merchant_expected_transfers met"
                         "  JOIN merchant_accounts mac"
                         "    USING (account_serial)"
                         "  LEFT JOIN merchant_transfer_signatures mts"
                         "    USING (expected_credit_serial)"
                         " WHERE ( $6 OR "
                         "         (mts.execution_time IS NOT NULL AND"
                         "          mts.execution_time < $1 AND"
                         "          mts.execution_time >= $2) )"
                         "   AND ( (CAST($5 AS TEXT) IS NULL) OR "
                         "         (REGEXP_REPLACE(mac.payto_uri,'\\?.*','')"
                         "         =REGEXP_REPLACE($5,'\\?.*','')) )"
                         "   AND ( $7 OR "
                         "         (met.confirmed = $8) )"
                         "   AND ( $9 OR "
                         "         ($10 = (200=met.last_http_status) AND"
                         "                (0=met.last_ec) ) )"
                         "   AND (met.expected_credit_serial < $3)"
                         " ORDER BY met.expected_credit_serial DESC"
                         " LIMIT $4");
  }
  qs = GNUNET_PQ_eval_prepared_multi_select (
    pg->conn,
    "",
    params,
    &lookup_expected_transfers_cb,
    &ltc);
  if (0 >= qs)
    return qs;
  return ltc.qs;
}
