/*
  This file is part of TALER
  Copyright (C) 2024 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/donau_api_donation_statement_get.c
 * @brief Implementation of the "handle" component of the donau's HTTP API
 * @author Lukas Matyja
 */
#include <gnunet/gnunet_curl_lib.h>
#include <taler/taler_json_lib.h>
#include "donau_service.h"
#include "donau_api_curl_defaults.h"
#include "donau_json_lib.h"


/**
 * Handle for a GET /donation-statement/$YEAR/$HASH_DONOR_ID request.
 */
struct DONAU_DonationStatementGetHandle
{
  /**
   * The url for the /donation-statement/$YEAR/$HASH_DONOR_ID request.
   */
  char *url;

  /**
   * Entry for this request with the `struct GNUNET_CURL_Context`.
   */
  struct GNUNET_CURL_Job *job;

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

  /**
   * Salted and hashed donor id
   */
  struct DONAU_HashDonorTaxId h_donor_tax_id;

  /**
   * year
   */
  uint64_t year;

  /**
   * Closure to pass to @e cb.
   */
  void *cb_cls;

};


/**
 * Callback used when downloading the reply to a /donation-statement/$YEAR/$HASH_DONOR_ID request
 * is complete.
 *
 * @param cls the `struct KeysRequest`
 * @param response_code HTTP response code, 0 on error
 * @param resp_obj parsed JSON result, NULL on error
 */
static void
handle_donation_statement_get_finished (void *cls,
                                        long response_code,
                                        const void *resp_obj)
{
  struct DONAU_DonationStatementGetHandle *dsgh = cls;
  const json_t *j = resp_obj;
  struct DONAU_DonationStatementResponse dsresp = {
    .hr.reply = j,
    .hr.http_status = (unsigned int) response_code
  };

  dsgh->job = NULL;
  switch (response_code)
  {
  case 0:
    dsresp.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_OK:
    {
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_fixed_auto (
          "donation_statement_sig",
          &dsresp.details.ok.donation_statement_sig),
        TALER_JSON_spec_amount_any ("total",
                                    &dsresp.details.ok.total_amount),
        GNUNET_JSON_spec_fixed_auto ("donau_pub",
                                     &dsresp.details.ok.donau_pub),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (j,
                             spec,
                             NULL,
                             NULL))
      {
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                    "Could not parse response from donation-statement GET\n");
        GNUNET_break_op (0);
        dsresp.hr.http_status = 0;
        dsresp.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
      }
      dsgh->cb (dsgh->cb_cls,
                &dsresp);
      dsgh->cb = NULL;
      break;
    }
  case MHD_HTTP_BAD_REQUEST:
    /* This should never happen, either us or the donau is buggy
       (or API version conflict); just pass JSON reply to the application */
    dsresp.hr.ec = TALER_JSON_get_error_code (j);
    dsresp.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  case MHD_HTTP_NOT_FOUND:
    /* Nothing really to verify, this should never
       happen, we should pass the JSON reply to the application */
    dsresp.hr.ec = TALER_JSON_get_error_code (j);
    dsresp.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    /* Server had an internal issue; we should retry, but this API
       leaves this to the application */
    dsresp.hr.ec = TALER_JSON_get_error_code (j);
    dsresp.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  default:
    /* unexpected response code */
    GNUNET_break_op (0);
    dsresp.hr.ec = TALER_JSON_get_error_code (j);
    dsresp.hr.hint = TALER_JSON_get_error_hint (j);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d for GET %s\n",
                (unsigned int) response_code,
                (int) dsresp.hr.ec,
                dsgh->url);
    break;
  }
  if (NULL != dsgh->cb)
  {
    dsgh->cb (dsgh->cb_cls,
              &dsresp);
    dsgh->cb = NULL;
  }
  DONAU_donation_statement_get_cancel (dsgh);
}


/**
 * Prepares the request URL for the age-withdraw request
 *
 * @param awbh The handler
 * @param donau_url The base-URL to the donau
 */
static
enum GNUNET_GenericReturnValue
prepare_url (
  struct DONAU_DonationStatementGetHandle *dsgh,
  const char *donau_url)
{
  char arg_str[sizeof (struct DONAU_HashDonorTaxId) * 2 + 32];
  char donor_id_hash_str[sizeof (struct DONAU_HashDonorTaxId) * 2];
  char *end;

  end = GNUNET_STRINGS_data_to_string (
    &dsgh->h_donor_tax_id,
    sizeof (struct DONAU_HashDonorTaxId),
    donor_id_hash_str,
    sizeof (donor_id_hash_str));
  *end = '\0';
  GNUNET_snprintf (arg_str,
                   sizeof (arg_str),
                   "donation-statement/%lu/%s",
                   dsgh->year,
                   donor_id_hash_str);

  dsgh->url = TALER_url_join (donau_url,
                              arg_str,
                              NULL);
  if (NULL == dsgh->url)
  {
    GNUNET_break (0);
    DONAU_donation_statement_get_cancel (dsgh);
    return GNUNET_SYSERR;
  }

  return GNUNET_OK;
}


struct DONAU_DonationStatementGetHandle *
DONAU_donation_statement_get (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const uint64_t year,
  const struct DONAU_HashDonorTaxId *h_donor_tax_id,
  DONAU_GetDonationStatmentResponseCallback cb,
  void *cb_cls)
{
  struct DONAU_DonationStatementGetHandle *dsgh;
  CURL *eh;

  TALER_LOG_DEBUG ("Connecting to the donau (%s)\n",
                   url);

  dsgh = GNUNET_new (struct DONAU_DonationStatementGetHandle);
  dsgh->cb = cb;
  dsgh->cb_cls = cb_cls;
  dsgh->year = year;
  dsgh->h_donor_tax_id = *h_donor_tax_id;
  if (GNUNET_OK != prepare_url (dsgh,
                                url))
    return NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Requesting a charity with URL `%s'.\n",
              dsgh->url);
  eh = DONAU_curl_easy_get_ (dsgh->url);
  if (NULL == eh)
  {
    GNUNET_break (0);
    GNUNET_free (dsgh->url);
    GNUNET_free (dsgh);
    return NULL;
  }
  dsgh->job = GNUNET_CURL_job_add_with_ct_json (ctx,
                                                eh,
                                                &
                                                handle_donation_statement_get_finished,
                                                dsgh);
  return dsgh;
}


void
DONAU_donation_statement_get_cancel (
  struct DONAU_DonationStatementGetHandle *dsgh)
{
  if (NULL != dsgh->job)
  {
    GNUNET_CURL_job_cancel (dsgh->job);
    dsgh->job = NULL;
  }
  GNUNET_free (dsgh->url);
  GNUNET_free (dsgh);
}
