/*
  This file is part of TALER
  (C) 2025 Taler Systems SA

  TALER 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.

  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 taler-merchant-httpd_private-get-incoming.c
 * @brief implement API for obtaining a list of expected incoming wire transfers
 * @author Christian Grothoff
 */
#include "platform.h"
#include <jansson.h>
#include <taler/taler_json_lib.h>
#include "taler-merchant-httpd_private-get-incoming.h"


/**
 * Function called with information about a wire transfer.
 * Generate a response (array entry) based on the given arguments.
 *
 * @param cls closure with a `json_t *` array to build up the response
 * @param expected_credit_amount amount expected to be wired to the merchant (minus fees), NULL if unknown
 * @param wtid wire transfer identifier
 * @param payto_uri target account that received the wire transfer
 * @param exchange_url base URL of the exchange that made the wire transfer
 * @param expected_transfer_serial_id serial number identifying the transfer in the backend
 * @param execution_time when did the exchange make the transfer, #GNUNET_TIME_UNIT_FOREVER_ABS
 *           if it did not yet happen
 * @param confirmed true if the merchant acknowledged the wire transfer reception
 * @param validated true if the reconciliation succeeded
 * @param last_http_status HTTP status of our last request to the exchange for this transfer
 * @param last_ec last error code we got back (otherwise #TALER_EC_NONE)
 * @param last_error_detail last detail we got back (or NULL for none)
 */
static void
incoming_cb (void *cls,
             const struct TALER_Amount *expected_credit_amount,
             const struct TALER_WireTransferIdentifierRawP *wtid,
             struct TALER_FullPayto payto_uri,
             const char *exchange_url,
             uint64_t expected_transfer_serial_id,
             struct GNUNET_TIME_Timestamp execution_time,
             bool confirmed,
             bool validated,
             unsigned int last_http_status,
             enum TALER_ErrorCode last_ec,
             const char *last_error_detail)
{
  json_t *ja = cls;
  json_t *r;

  r = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_allow_null (
      TALER_JSON_pack_amount ("expected_credit_amount",
                              expected_credit_amount)),
    GNUNET_JSON_pack_data_auto ("wtid",
                                wtid),
    TALER_JSON_pack_full_payto ("payto_uri",
                                payto_uri),
    GNUNET_JSON_pack_string ("exchange_url",
                             exchange_url),
    GNUNET_JSON_pack_uint64 ("expected_transfer_serial_id",
                             expected_transfer_serial_id),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_timestamp ("execution_time",
                                  execution_time)),
    GNUNET_JSON_pack_bool ("validated",
                           validated),
    GNUNET_JSON_pack_bool ("confirmed",
                           confirmed),
    GNUNET_JSON_pack_uint64 ("last_http_status",
                             last_http_status),
    GNUNET_JSON_pack_uint64 ("last_ec",
                             last_ec),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_string ("last_error_detail",
                               last_error_detail)));
  GNUNET_assert (0 ==
                 json_array_append_new (ja,
                                        r));
}


/**
 * Manages a GET /private/incoming call.
 *
 * @param rh context of the handler
 * @param connection the MHD connection to handle
 * @param[in,out] hc context with further information about the request
 * @return MHD result code
 */
MHD_RESULT
TMH_private_get_incoming (const struct TMH_RequestHandler *rh,
                          struct MHD_Connection *connection,
                          struct TMH_HandlerContext *hc)
{
  struct TALER_FullPayto payto_uri = {
    .full_payto = NULL
  };
  struct GNUNET_TIME_Timestamp before = GNUNET_TIME_UNIT_FOREVER_TS;
  struct GNUNET_TIME_Timestamp after = GNUNET_TIME_UNIT_ZERO_TS;
  int64_t limit = -20;
  uint64_t offset;
  enum TALER_EXCHANGE_YesNoAll confirmed;
  enum TALER_EXCHANGE_YesNoAll verified;

  (void) rh;
  TALER_MHD_parse_request_snumber (connection,
                                   "limit",
                                   &limit);
  if (limit < 0)
    offset = INT64_MAX;
  else
    offset = 0;
  TALER_MHD_parse_request_number (connection,
                                  "offset",
                                  &offset);
  TALER_MHD_parse_request_yna (connection,
                               "verified",
                               TALER_EXCHANGE_YNA_ALL,
                               &verified);
  TALER_MHD_parse_request_yna (connection,
                               "confirmed",
                               TALER_EXCHANGE_YNA_ALL,
                               &confirmed);
  TALER_MHD_parse_request_timestamp (connection,
                                     "before",
                                     &before);
  TALER_MHD_parse_request_timestamp (connection,
                                     "after",
                                     &after);
  {
    const char *esc_payto;

    esc_payto = MHD_lookup_connection_value (connection,
                                             MHD_GET_ARGUMENT_KIND,
                                             "payto_uri");
    if (NULL != esc_payto)
    {
      payto_uri.full_payto
        = GNUNET_strdup (esc_payto);
      (void) MHD_http_unescape (payto_uri.full_payto);
    }
  }
  TMH_db->preflight (TMH_db->cls);
  {
    json_t *ja;
    enum GNUNET_DB_QueryStatus qs;

    ja = json_array ();
    GNUNET_assert (NULL != ja);
    qs = TMH_db->lookup_expected_transfers (TMH_db->cls,
                                            hc->instance->settings.id,
                                            payto_uri,
                                            before,
                                            after,
                                            limit,
                                            offset,
                                            confirmed,
                                            verified,
                                            &incoming_cb,
                                            ja);
    GNUNET_free (payto_uri.full_payto);
    if (0 > qs)
    {
      /* Simple select queries should not cause serialization issues */
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR != qs);
      /* Always report on hard error as well to enable diagnostics */
      GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR == qs);
      return TALER_MHD_reply_with_error (connection,
                                         MHD_HTTP_INTERNAL_SERVER_ERROR,
                                         TALER_EC_GENERIC_DB_FETCH_FAILED,
                                         "incoming");
    }
    return TALER_MHD_REPLY_JSON_PACK (
      connection,
      MHD_HTTP_OK,
      GNUNET_JSON_pack_array_steal ("incoming",
                                    ja));
  }
}


/* end of taler-merchant-httpd_private-get-incoming.c */
