/*
   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 backenddb/pg_lookup_reconciliation_details.c
 * @brief Implementation of the lookup_reconciliation_details function for Postgres
 * @author Christian Grothoff
 */
#include "taler/platform.h"
#include <taler/taler_error_codes.h>
#include <taler/taler_dbevents.h>
#include <taler/taler_pq_lib.h>
#include "pg_lookup_reconciliation_details.h"
#include "pg_helper.h"


/**
 * Context for TMH_PG_lookup_reconciliation_details().
 */
struct ReconciliationContext
{
  /**
   * Function to call with the results.
   */
  TALER_MERCHANTDB_ReconciliationDetailsCallback cb;

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

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

  /**
   * Set to the return value on errors.
   */
  enum GNUNET_DB_QueryStatus qs;

};


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

  for (unsigned int i = 0; i < num_results; i++)
  {
    char *order_id;
    uint64_t dvs;
    uint64_t dfs;
    uint64_t fvs;
    uint64_t ffs;
    char *currency;
    struct TALER_Amount remaining_deposit;
    struct TALER_Amount deposit_fee;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_string ("order_id",
                                    &order_id),
      GNUNET_PQ_result_spec_string ("currency",
                                    &currency),
      GNUNET_PQ_result_spec_uint64 ("deposit_value_sum",
                                    &dvs),
      GNUNET_PQ_result_spec_uint64 ("deposit_frac_sum",
                                    &dfs),
      GNUNET_PQ_result_spec_uint64 ("fee_value_sum",
                                    &fvs),
      GNUNET_PQ_result_spec_uint64 ("fee_frac_sum",
                                    &ffs),
      GNUNET_PQ_result_spec_end
    };

    if (GNUNET_OK !=
        GNUNET_PQ_extract_result (result,
                                  rs,
                                  i))
    {
      GNUNET_break (0);
      lic->qs = GNUNET_DB_STATUS_HARD_ERROR;
      return;
    }
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_set_zero (currency,
                                          &remaining_deposit));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_set_zero (currency,
                                          &deposit_fee));
    remaining_deposit.value = dvs + dfs / TALER_AMOUNT_FRAC_BASE;
    remaining_deposit.fraction = dfs % TALER_AMOUNT_FRAC_BASE;
    deposit_fee.value = fvs + ffs / TALER_AMOUNT_FRAC_BASE;
    deposit_fee.fraction = ffs % TALER_AMOUNT_FRAC_BASE;

    lic->cb (lic->cb_cls,
             order_id,
             &remaining_deposit,
             &deposit_fee);
    GNUNET_PQ_cleanup_result (rs);
  }
}


enum GNUNET_DB_QueryStatus
TMH_PG_lookup_reconciliation_details (
  void *cls,
  const char *instance_id,
  uint64_t expected_incoming_serial,
  TALER_MERCHANTDB_ReconciliationDetailsCallback cb,
  void *cb_cls)
{
  struct PostgresClosure *pg = cls;
  struct ReconciliationContext lic = {
    .cb = cb,
    .cb_cls = cb_cls,
    .pg = pg
  };
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_string (instance_id),
    GNUNET_PQ_query_param_uint64 (&expected_incoming_serial),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  PREPARE (pg,
           "lookup_reconciliation_details",
           "SELECT"
           " mct.order_id"
           ",SUM((etc.exchange_deposit_value).val)::INT8 AS deposit_value_sum"
           ",SUM((etc.exchange_deposit_value).frac)::INT8 AS deposit_frac_sum"
           ",SUM((etc.exchange_deposit_fee).val)::INT8 AS fee_value_sum"
           ",SUM((etc.exchange_deposit_fee).frac)::INT8 AS fee_frac_sum"
           ",(etc.exchange_deposit_value).curr AS currency"
           " FROM merchant_expected_transfer_to_coin etc"
           " JOIN merchant_deposits md"
           "   USING (deposit_serial)"
           " JOIN merchant_deposit_confirmations mdc"
           "   USING (deposit_confirmation_serial)"
           " JOIN merchant_contract_terms mct"
           "   USING (order_serial)"
           " JOIN merchant_instances mi"
           "   USING (merchant_serial)"
           " WHERE expected_credit_serial=$2"
           "   AND mi.merchant_id=$1"
           " GROUP BY mct.order_id, (etc.exchange_deposit_value).curr;");
  qs = GNUNET_PQ_eval_prepared_multi_select (pg->conn,
                                             "lookup_reconciliation_details",
                                             params,
                                             &reconciliation_cb,
                                             &lic);
  if (0 > lic.qs)
    return lic.qs;
  return qs;
}
