/*
  This file is part of TALER
  Copyright (C) 2014-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_get-reserves-RESERVE_PUB-attest.c
 * @brief Implementation of the GET /reserves/$RESERVE_PUB/attest request
 * @author Christian Grothoff
 */
#include <jansson.h>
#include <microhttpd.h> /* just for HTTP status codes */
#include <gnunet/gnunet_util_lib.h>
#include <gnunet/gnunet_json_lib.h>
#include <gnunet/gnunet_curl_lib.h>
#include "taler/taler_json_lib.h"
#include "exchange_api_handle.h"
#include "taler/taler_signatures.h"
#include "exchange_api_curl_defaults.h"


/**
 * @brief A GET /reserves/$RESERVE_PUB/attest Handle
 */
struct TALER_EXCHANGE_GetReservesAttestHandle
{

  /**
   * Base URL of the exchange.
   */
  char *base_url;

  /**
   * The url for this request.
   */
  char *url;

  /**
   * CURL context to use.
   */
  struct GNUNET_CURL_Context *ctx;

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

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

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

  /**
   * Public key of the reserve we are querying.
   */
  struct TALER_ReservePublicKeyP reserve_pub;

};


/**
 * We received an #MHD_HTTP_OK status code. Handle the JSON response.
 *
 * @param grah handle of the request
 * @param j JSON response
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
handle_reserves_get_attestable_ok (
  struct TALER_EXCHANGE_GetReservesAttestHandle *grah,
  const json_t *j)
{
  struct TALER_EXCHANGE_GetReservesAttestResponse rs = {
    .hr.reply = j,
    .hr.http_status = MHD_HTTP_OK
  };
  const json_t *details;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_array_const ("details",
                                  &details),
    GNUNET_JSON_spec_end ()
  };

  if (GNUNET_OK !=
      GNUNET_JSON_parse (j,
                         spec,
                         NULL,
                         NULL))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  {
    size_t dlen = json_array_size (details);
    const char *attributes[GNUNET_NZL (dlen)];

    for (unsigned int i = 0; i < dlen; i++)
    {
      json_t *detail = json_array_get (details,
                                       i);
      attributes[i] = json_string_value (detail);
      if (NULL == attributes[i])
      {
        GNUNET_break_op (0);
        return GNUNET_SYSERR;
      }
    }
    rs.details.ok.attributes_length = dlen;
    rs.details.ok.attributes = attributes;
    grah->cb (grah->cb_cls,
              &rs);
    grah->cb = NULL;
  }
  return GNUNET_OK;
}


/**
 * Function called when we're done processing the
 * HTTP GET /reserves/$RESERVE_PUB/attest request.
 *
 * @param cls the `struct TALER_EXCHANGE_GetReservesAttestHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response parsed JSON result, NULL on error
 */
static void
handle_reserves_get_attestable_finished (void *cls,
                                         long response_code,
                                         const void *response)
{
  struct TALER_EXCHANGE_GetReservesAttestHandle *grah = cls;
  const json_t *j = response;
  struct TALER_EXCHANGE_GetReservesAttestResponse rs = {
    .hr.reply = j,
    .hr.http_status = (unsigned int) response_code
  };

  grah->job = NULL;
  switch (response_code)
  {
  case 0:
    rs.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_OK:
    if (GNUNET_OK !=
        handle_reserves_get_attestable_ok (grah,
                                           j))
    {
      rs.hr.http_status = 0;
      rs.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
    }
    break;
  case MHD_HTTP_BAD_REQUEST:
    /* This should never happen, either us or the exchange is buggy
       (or API version conflict); just pass JSON reply to the application */
    rs.hr.ec = TALER_JSON_get_error_code (j);
    rs.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 */
    rs.hr.ec = TALER_JSON_get_error_code (j);
    rs.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  case MHD_HTTP_CONFLICT:
    /* Nothing really to verify, this should never
       happen, we should pass the JSON reply to the application */
    rs.hr.ec = TALER_JSON_get_error_code (j);
    rs.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 */
    rs.hr.ec = TALER_JSON_get_error_code (j);
    rs.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  default:
    /* unexpected response code */
    GNUNET_break_op (0);
    rs.hr.ec = TALER_JSON_get_error_code (j);
    rs.hr.hint = TALER_JSON_get_error_hint (j);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d for reserves get_attestable\n",
                (unsigned int) response_code,
                (int) rs.hr.ec);
    break;
  }
  if (NULL != grah->cb)
  {
    grah->cb (grah->cb_cls,
              &rs);
    grah->cb = NULL;
  }
  TALER_EXCHANGE_get_reserves_attest_cancel (grah);
}


struct TALER_EXCHANGE_GetReservesAttestHandle *
TALER_EXCHANGE_get_reserves_attest_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const struct TALER_ReservePublicKeyP *reserve_pub)
{
  struct TALER_EXCHANGE_GetReservesAttestHandle *grah;

  grah = GNUNET_new (struct TALER_EXCHANGE_GetReservesAttestHandle);
  grah->ctx = ctx;
  grah->base_url = GNUNET_strdup (url);
  grah->reserve_pub = *reserve_pub;
  return grah;
}


enum TALER_ErrorCode
TALER_EXCHANGE_get_reserves_attest_start (
  struct TALER_EXCHANGE_GetReservesAttestHandle *grah,
  TALER_EXCHANGE_GetReservesAttestCallback cb,
  TALER_EXCHANGE_GET_RESERVES_ATTEST_RESULT_CLOSURE *cb_cls)
{
  char arg_str[sizeof (struct TALER_ReservePublicKeyP) * 2 + 32];
  CURL *eh;

  if (NULL != grah->job)
  {
    GNUNET_break (0);
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  grah->cb = cb;
  grah->cb_cls = cb_cls;
  {
    char pub_str[sizeof (struct TALER_ReservePublicKeyP) * 2];
    char *end;

    end = GNUNET_STRINGS_data_to_string (
      &grah->reserve_pub,
      sizeof (grah->reserve_pub),
      pub_str,
      sizeof (pub_str));
    *end = '\0';
    GNUNET_snprintf (arg_str,
                     sizeof (arg_str),
                     "reserves/%s/attest",
                     pub_str);
  }
  grah->url = TALER_url_join (grah->base_url,
                              arg_str,
                              NULL);
  if (NULL == grah->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  eh = TALER_EXCHANGE_curl_easy_get_ (grah->url);
  if (NULL == eh)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  grah->job = GNUNET_CURL_job_add (grah->ctx,
                                   eh,
                                   &handle_reserves_get_attestable_finished,
                                   grah);
  if (NULL == grah->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_EXCHANGE_get_reserves_attest_cancel (
  struct TALER_EXCHANGE_GetReservesAttestHandle *grah)
{
  if (NULL != grah->job)
  {
    GNUNET_CURL_job_cancel (grah->job);
    grah->job = NULL;
  }
  GNUNET_free (grah->url);
  GNUNET_free (grah->base_url);
  GNUNET_free (grah);
}


/* end of exchange_api_get-reserves-RESERVE_PUB-attest.c */
