/*
  This file is part of TALER
  Copyright (C) 2014-2023 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_instance.c
 * @brief Implementation of the GET /instance/$ID request of the merchant's HTTP API
 * @author Christian Grothoff
 */
#include "platform.h"
#include <curl/curl.h>
#include <jansson.h>
#include <microhttpd.h> /* just 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_kyclogic_lib.h>
#include <taler/taler_signatures.h>


/**
 * Handle for a GET /instances/$ID operation.
 */
struct TALER_MERCHANT_InstanceGetHandle
{
  /**
   * The url for this request.
   */
  char *url;

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

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

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

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

};


/**
 * Function called when we're done processing the
 * HTTP GET /instances/$ID request.
 *
 * @param cls the `struct TALER_MERCHANT_InstanceGetHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_get_instance_finished (void *cls,
                              long response_code,
                              const void *response)
{
  struct TALER_MERCHANT_InstanceGetHandle *igh = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_InstanceGetResponse igr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  igh->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Got /instances/$ID response with status code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case MHD_HTTP_OK:
    {
      const json_t *address;
      const json_t *jurisdiction;
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_string (
          "name",
          &igr.details.ok.details.name),
        GNUNET_JSON_spec_fixed_auto (
          "merchant_pub",
          &igr.details.ok.details.merchant_pub),
        GNUNET_JSON_spec_object_const (
          "address",
          &address),
        GNUNET_JSON_spec_object_const (
          "jurisdiction",
          &jurisdiction),
        GNUNET_JSON_spec_bool (
          "use_stefan",
          &igr.details.ok.details.use_stefan),
        GNUNET_JSON_spec_relative_time (
          "default_wire_transfer_delay",
          &igr.details.ok.details.default_wire_transfer_delay),
        GNUNET_JSON_spec_relative_time (
          "default_pay_delay",
          &igr.details.ok.details.default_pay_delay),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_relative_time (
            "default_refund_delay",
            &igr.details.ok.details.default_refund_delay),
          NULL),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_time_rounder_interval (
            "default_wire_transfer_rounding_interval",
            &igr.details.ok.details.default_wire_transfer_rounding_interval),
          NULL),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json,
                             spec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        igr.hr.http_status = 0;
        igr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
      igr.details.ok.details.address = address;
      igr.details.ok.details.jurisdiction = jurisdiction;
      igh->cb (igh->cb_cls,
               &igr);
      TALER_MERCHANT_instance_get_cancel (igh);
      return;
    }
  case MHD_HTTP_UNAUTHORIZED:
    igr.hr.ec = TALER_JSON_get_error_code (json);
    igr.hr.hint = TALER_JSON_get_error_hint (json);
    /* Nothing really to verify, merchant says we need to authenticate. */
    break;
  case MHD_HTTP_NOT_FOUND:
    /* instance does not exist */
    igr.hr.ec = TALER_JSON_get_error_code (json);
    igr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    /* unexpected response code */
    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;
  }
  igh->cb (igh->cb_cls,
           &igr);
  TALER_MERCHANT_instance_get_cancel (igh);
}


struct TALER_MERCHANT_InstanceGetHandle *
TALER_MERCHANT_instance_get (struct GNUNET_CURL_Context *ctx,
                             const char *backend_url,
                             const char *instance_id,
                             TALER_MERCHANT_InstanceGetCallback cb,
                             void *cb_cls)
{
  struct TALER_MERCHANT_InstanceGetHandle *igh;
  CURL *eh;

  igh = GNUNET_new (struct TALER_MERCHANT_InstanceGetHandle);
  igh->ctx = ctx;
  igh->cb = cb;
  igh->cb_cls = cb_cls;
  if (NULL != instance_id)
  {
    char *path;

    GNUNET_asprintf (&path,
                     "instances/%s/private",
                     instance_id);
    igh->url = TALER_url_join (backend_url,
                               path,
                               NULL);
    GNUNET_free (path);
  }
  else
  {
    igh->url = TALER_url_join (backend_url,
                               "private",
                               NULL);
  }
  if (NULL == igh->url)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Could not construct request URL.\n");
    GNUNET_free (igh);
    return NULL;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Requesting URL '%s'\n",
              igh->url);
  eh = TALER_MERCHANT_curl_easy_get_ (igh->url);
  igh->job = GNUNET_CURL_job_add (ctx,
                                  eh,
                                  &handle_get_instance_finished,
                                  igh);
  return igh;
}


void
TALER_MERCHANT_instance_get_cancel (
  struct TALER_MERCHANT_InstanceGetHandle *igh)
{
  if (NULL != igh->job)
    GNUNET_CURL_job_cancel (igh->job);
  GNUNET_free (igh->url);
  GNUNET_free (igh);
}
