/*
  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 Lesser General Public License as published by the Free Software
  Foundation; either version 2.1, 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 Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public License along with
  TALER; see the file COPYING.LGPL.  If not, see <http://www.gnu.org/licenses/>
 */
/**
 * @file merchant_api_get_donau_instance.c
 * @brief Implementation of the GET /donau request of the merchant's HTTP API
 * @author Bohdan Potuzhnyi
 * @author Vlada Svirsh
 */

#include "platform.h"
#include <curl/curl.h>
#include <jansson.h>
#include <microhttpd.h> /* for HTTP status codes */
#include <gnunet/gnunet_util_lib.h>
#include <gnunet/gnunet_curl_lib.h>
#include "taler_merchant_service.h"
#include "merchant_api_curl_defaults.h"
#include <taler/taler_json_lib.h>
#include <taler/taler_signatures.h>
/* DONAU RELATED IMPORTS */
#include "taler_merchant_donau.h"
#include <donau/donau_service.h>

/**
 * Handle for a GET /donau operation.
 */
struct TALER_MERCHANT_DonauInstanceGetHandle
{
  /**
   * The URL for this request.
   */
  char *url;

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

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

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

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

/**
 * Parse Donau instance information from @a ia.
 *
 * @param ia JSON array (or NULL!) with Donau instance data
 * @param igr response to fill
 * @param dgh operation handle
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_donau_instances (const json_t *ia,
                       struct TALER_MERCHANT_DonauInstanceGetResponse *igr,
                       struct TALER_MERCHANT_DonauInstanceGetHandle *dgh)
{
  unsigned int instances_len = (unsigned int) json_array_size (ia);
  struct TALER_MERCHANT_DonauInstanceEntry
    instances[GNUNET_NZL (instances_len)];
  size_t index;
  json_t *value;
  struct DONAU_Keys *donau_keys_ptr = NULL;

  if ((json_array_size (ia) != (size_t) instances_len))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  json_array_foreach (ia,
                      index,
                      value)
  {
    struct TALER_MERCHANT_DonauInstanceEntry *instance = &instances[index];
    const json_t *donau_keys_json = NULL;
    struct GNUNET_JSON_Specification spec[] = {
      GNUNET_JSON_spec_uint64 ("donau_instance_serial",
                               &instance->donau_instance_serial),
      GNUNET_JSON_spec_string ("donau_url",
                               &instance->donau_url),
      GNUNET_JSON_spec_string ("charity_name",
                               &instance->charity_name),
      GNUNET_JSON_spec_fixed_auto ("charity_pub_key",
                                   &instance->charity_pub_key),
      GNUNET_JSON_spec_uint64 ("charity_id",
                               &instance->charity_id),
      TALER_JSON_spec_amount_any ("charity_max_per_year",
                                  &instance->charity_max_per_year),
      TALER_JSON_spec_amount_any ("charity_receipts_to_date",
                                  &instance->charity_receipts_to_date),
      GNUNET_JSON_spec_int64 ("current_year",
                              &instance->current_year),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_object_const ("donau_keys_json",
                                       &donau_keys_json),
        NULL),
      GNUNET_JSON_spec_end ()
    };

    if (GNUNET_OK !=
        GNUNET_JSON_parse (value,
                           spec,
                           NULL,
                           NULL))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }

    /* Parse the Donau keys */
    if (NULL != donau_keys_json)
    {
      donau_keys_ptr = DONAU_keys_from_json (donau_keys_json);
      if (NULL == donau_keys_ptr)
      {
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                    "Failed to convert donau keys from JSON\n");
        return GNUNET_SYSERR;
      }
      instance->donau_keys = donau_keys_ptr;
    }
  }

  igr->details.ok.donau_instances_length = instances_len;
  igr->details.ok.donau_instances = instances;
  dgh->cb (dgh->cb_cls,
           igr);
  dgh->cb = NULL;
  if (NULL != donau_keys_ptr)
  {
    DONAU_keys_decref (donau_keys_ptr);
    donau_keys_ptr= NULL;
  }
  return GNUNET_OK;
}


/**
 * Function called when we're done processing the
 * HTTP /donau request.
 *
 * @param cls the `struct TALER_MERCHANT_DonauInstanceGetHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_get_donau_instances_finished (void *cls,
                                     long response_code,
                                     const void *response)
{
  struct TALER_MERCHANT_DonauInstanceGetHandle *dgh = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_DonauInstanceGetResponse igr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  dgh->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Got /donau response with status code %u\n",
              (unsigned int) response_code);

  switch (response_code)
  {
  case MHD_HTTP_OK:
    {
      const json_t *donau_instances;
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_array_const ("donau_instances",
                                      &donau_instances),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json,
                             spec,
                             NULL,
                             NULL))
      {
        igr.hr.http_status = 0;
        igr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }

      if (GNUNET_OK ==
          parse_donau_instances (donau_instances,
                                 &igr,
                                 dgh))
      {
        TALER_MERCHANT_donau_instances_get_cancel (dgh);
        return;
      }

      igr.hr.http_status = 0;
      igr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
      break;
    }

  case MHD_HTTP_UNAUTHORIZED:
  case MHD_HTTP_NOT_FOUND:
  default:
    igr.hr.ec = TALER_JSON_get_error_code (json);
    igr.hr.hint = TALER_JSON_get_error_hint (json);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d\n",
                (unsigned int) response_code,
                (int) igr.hr.ec);
    break;
  }

  dgh->cb (dgh->cb_cls,
           &igr);
  TALER_MERCHANT_donau_instances_get_cancel (dgh);
}


/**
 * Initiate the GET /donau request.
 *
 * @param ctx CURL context
 * @param backend_url base URL for the backend
 * @param cb callback function to handle the response
 * @param cb_cls closure for the callback function
 * @return the handle for the operation, or NULL on error
 */
struct TALER_MERCHANT_DonauInstanceGetHandle *
TALER_MERCHANT_donau_instances_get (struct GNUNET_CURL_Context *ctx,
                                    const char *backend_url,
                                    TALER_MERCHANT_DonauInstanceGetCallback cb,
                                    void *cb_cls)
{
  struct TALER_MERCHANT_DonauInstanceGetHandle *dgh;
  CURL *eh;

  dgh = GNUNET_new (struct TALER_MERCHANT_DonauInstanceGetHandle);
  dgh->ctx = ctx;
  dgh->cb = cb;
  dgh->cb_cls = cb_cls;
  dgh->url = TALER_url_join (backend_url,
                             "private/donau",
                             NULL);
  if (NULL == dgh->url)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Could not construct request URL.\n");
    GNUNET_free (dgh);
    return NULL;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Requesting URL '%s'\n",
              dgh->url);
  eh = TALER_MERCHANT_curl_easy_get_ (dgh->url);
  dgh->job = GNUNET_CURL_job_add (ctx,
                                  eh,
                                  &handle_get_donau_instances_finished,
                                  dgh);

  return dgh;
}


/**
 * Cancel the GET /donau instances operation.
 *
 * @param dgh request to cancel.
 */
void
TALER_MERCHANT_donau_instances_get_cancel (
  struct TALER_MERCHANT_DonauInstanceGetHandle *dgh)
{
  if (NULL != dgh->job)
    GNUNET_CURL_job_cancel (dgh->job);
  GNUNET_free (dgh->url);
  GNUNET_free (dgh);
}
