/*
  This file is part of TALER
  Copyright (C) 2020-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 lib/exchange_api_post-management-drain.c
 * @brief functions to drain profits from an exchange account
 * @author Christian Grothoff
 */
#include "taler/taler_json_lib.h"
#include <gnunet/gnunet_curl_lib.h>
#include <microhttpd.h>
#include "taler/exchange/post-management-drain.h"
#include "exchange_api_curl_defaults.h"
#include "taler/taler_curl_lib.h"


struct TALER_EXCHANGE_PostManagementDrainHandle
{

  /**
   * The base URL for this request.
   */
  char *base_url;

  /**
   * The full URL for this request, set during _start.
   */
  char *url;

  /**
   * Minor context that holds body and headers.
   */
  struct TALER_CURL_PostContext post_ctx;

  /**
   * Handle for the request.
   */
  struct GNUNET_CURL_Job *job;

  /**
   * Function to call with the result.
   */
  TALER_EXCHANGE_PostManagementDrainCallback cb;

  /**
   * Closure for @a cb.
   */
  TALER_EXCHANGE_POST_MANAGEMENT_DRAIN_RESULT_CLOSURE *cb_cls;

  /**
   * Reference to the execution context.
   */
  struct GNUNET_CURL_Context *ctx;

  /**
   * Wire transfer identifier to use.
   */
  struct TALER_WireTransferIdentifierRawP wtid;

  /**
   * Total to transfer.
   */
  struct TALER_Amount amount;

  /**
   * When was the request created.
   */
  struct GNUNET_TIME_Timestamp date;

  /**
   * Configuration section identifying account to debit.
   */
  char *account_section;

  /**
   * Payto URI of the account to credit.
   */
  char *payto_uri_str;

  /**
   * Signature affirming the operation.
   */
  struct TALER_MasterSignatureP master_sig;

};


/**
 * Function called when we're done processing the
 * HTTP POST /management/drain request.
 *
 * @param cls the `struct TALER_EXCHANGE_PostManagementDrainHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_drain_finished (void *cls,
                       long response_code,
                       const void *response)
{
  struct TALER_EXCHANGE_PostManagementDrainHandle *pmdh = cls;
  const json_t *json = response;
  struct TALER_EXCHANGE_PostManagementDrainResponse res = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  pmdh->job = NULL;
  switch (response_code)
  {
  case MHD_HTTP_NO_CONTENT:
    break;
  case MHD_HTTP_FORBIDDEN:
    res.hr.ec = TALER_JSON_get_error_code (json);
    res.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    res.hr.ec = TALER_JSON_get_error_code (json);
    res.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    /* unexpected response code */
    GNUNET_break_op (0);
    res.hr.ec = TALER_JSON_get_error_code (json);
    res.hr.hint = TALER_JSON_get_error_hint (json);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d for exchange management drain profits\n",
                (unsigned int) response_code,
                (int) res.hr.ec);
    break;
  }
  if (NULL != pmdh->cb)
  {
    pmdh->cb (pmdh->cb_cls,
              &res);
    pmdh->cb = NULL;
  }
  TALER_EXCHANGE_post_management_drain_cancel (pmdh);
}


struct TALER_EXCHANGE_PostManagementDrainHandle *
TALER_EXCHANGE_post_management_drain_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const struct TALER_WireTransferIdentifierRawP *wtid,
  const struct TALER_Amount *amount,
  struct GNUNET_TIME_Timestamp date,
  const char *account_section,
  const struct TALER_FullPayto payto_uri,
  const struct TALER_MasterSignatureP *master_sig)
{
  struct TALER_EXCHANGE_PostManagementDrainHandle *pmdh;

  pmdh = GNUNET_new (struct TALER_EXCHANGE_PostManagementDrainHandle);
  pmdh->ctx = ctx;
  pmdh->base_url = GNUNET_strdup (url);
  pmdh->wtid = *wtid;
  pmdh->amount = *amount;
  pmdh->date = date;
  pmdh->account_section = GNUNET_strdup (account_section);
  pmdh->payto_uri_str = GNUNET_strdup (payto_uri.full_payto);
  pmdh->master_sig = *master_sig;
  return pmdh;
}


enum TALER_ErrorCode
TALER_EXCHANGE_post_management_drain_start (
  struct TALER_EXCHANGE_PostManagementDrainHandle *pmdh,
  TALER_EXCHANGE_PostManagementDrainCallback cb,
  TALER_EXCHANGE_POST_MANAGEMENT_DRAIN_RESULT_CLOSURE *cb_cls)
{
  CURL *eh;
  json_t *body;
  struct TALER_FullPayto payto_uri = {
    .full_payto = pmdh->payto_uri_str
  };

  pmdh->cb = cb;
  pmdh->cb_cls = cb_cls;
  pmdh->url = TALER_url_join (pmdh->base_url,
                              "management/drain",
                              NULL);
  if (NULL == pmdh->url)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Could not construct request URL.\n");
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  }
  body = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_string ("debit_account_section",
                             pmdh->account_section),
    TALER_JSON_pack_full_payto ("credit_payto_uri",
                                payto_uri),
    GNUNET_JSON_pack_data_auto ("wtid",
                                &pmdh->wtid),
    GNUNET_JSON_pack_data_auto ("master_sig",
                                &pmdh->master_sig),
    GNUNET_JSON_pack_timestamp ("date",
                                pmdh->date),
    TALER_JSON_pack_amount ("amount",
                            &pmdh->amount));
  eh = TALER_EXCHANGE_curl_easy_get_ (pmdh->url);
  if ( (NULL == eh) ||
       (GNUNET_OK !=
        TALER_curl_easy_post (&pmdh->post_ctx,
                              eh,
                              body)) )
  {
    GNUNET_break (0);
    if (NULL != eh)
      curl_easy_cleanup (eh);
    json_decref (body);
    GNUNET_free (pmdh->url);
    pmdh->url = NULL;
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  json_decref (body);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Requesting URL '%s'\n",
              pmdh->url);
  pmdh->job = GNUNET_CURL_job_add2 (pmdh->ctx,
                                    eh,
                                    pmdh->post_ctx.headers,
                                    &handle_drain_finished,
                                    pmdh);
  if (NULL == pmdh->job)
  {
    TALER_curl_easy_post_finished (&pmdh->post_ctx);
    GNUNET_free (pmdh->url);
    pmdh->url = NULL;
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  return TALER_EC_NONE;
}


void
TALER_EXCHANGE_post_management_drain_cancel (
  struct TALER_EXCHANGE_PostManagementDrainHandle *pmdh)
{
  if (NULL != pmdh->job)
  {
    GNUNET_CURL_job_cancel (pmdh->job);
    pmdh->job = NULL;
  }
  TALER_curl_easy_post_finished (&pmdh->post_ctx);
  GNUNET_free (pmdh->account_section);
  GNUNET_free (pmdh->payto_uri_str);
  GNUNET_free (pmdh->url);
  GNUNET_free (pmdh->base_url);
  GNUNET_free (pmdh);
}


/* end of exchange_api_post-management-drain.c */
