/*
  This file is part of TALER
  Copyright (C) 2022-2026 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 src/lib/merchant_api_get-private-webhooks.c
 * @brief Implementation of the GET /private/webhooks request
 * @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/get-private-webhooks.h>
#include "merchant_api_curl_defaults.h"
#include <taler/taler_json_lib.h>


/**
 * Maximum number of webhooks permitted.
 */
#define MAX_WEBHOOKS 1024


/**
 * Handle for a GET /private/webhooks operation.
 */
struct TALER_MERCHANT_GetPrivateWebhooksHandle
{
  /**
   * Base URL of the merchant backend.
   */
  char *base_url;

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

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

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

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

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


/**
 * Parse webhook information from @a ia.
 *
 * @param ia JSON array (or NULL!) with webhook data
 * @param[in] wgr partially filled webhook response
 * @param gpwh operation handle
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_webhooks (const json_t *ia,
                struct TALER_MERCHANT_GetPrivateWebhooksResponse *wgr,
                struct TALER_MERCHANT_GetPrivateWebhooksHandle *gpwh)
{
  unsigned int whook_len = (unsigned int) json_array_size (ia);

  if ( (json_array_size (ia) != (size_t) whook_len) ||
       (whook_len > MAX_WEBHOOKS) )
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  {
    struct TALER_MERCHANT_GetPrivateWebhooksWebhookEntry whook[
      GNUNET_NZL (whook_len)];
    size_t index;
    json_t *value;

    json_array_foreach (ia, index, value) {
      struct TALER_MERCHANT_GetPrivateWebhooksWebhookEntry *ie =
        &whook[index];
      struct GNUNET_JSON_Specification spec[] = {
        TALER_JSON_spec_slug ("webhook_id",
                              &ie->webhook_id),
        GNUNET_JSON_spec_string ("event_type",
                                 &ie->event_type),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (value,
                             spec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        return GNUNET_SYSERR;
      }
    }
    wgr->details.ok.webhooks_length = whook_len;
    wgr->details.ok.webhooks = whook;
    gpwh->cb (gpwh->cb_cls,
              wgr);
    gpwh->cb = NULL;
  }
  return GNUNET_OK;
}


/**
 * Function called when we're done processing the
 * HTTP GET /private/webhooks request.
 *
 * @param cls the `struct TALER_MERCHANT_GetPrivateWebhooksHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_get_webhooks_finished (void *cls,
                              long response_code,
                              const void *response)
{
  struct TALER_MERCHANT_GetPrivateWebhooksHandle *gpwh = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_GetPrivateWebhooksResponse wgr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  gpwh->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Got /private/webhooks response with status code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case MHD_HTTP_OK:
    {
      const json_t *webhooks;
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_array_const ("webhooks",
                                      &webhooks),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json,
                             spec,
                             NULL, NULL))
      {
        wgr.hr.http_status = 0;
        wgr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
      if (GNUNET_OK ==
          parse_webhooks (webhooks,
                          &wgr,
                          gpwh))
      {
        TALER_MERCHANT_get_private_webhooks_cancel (gpwh);
        return;
      }
      wgr.hr.http_status = 0;
      wgr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
      break;
    }
  case MHD_HTTP_UNAUTHORIZED:
    wgr.hr.ec = TALER_JSON_get_error_code (json);
    wgr.hr.hint = TALER_JSON_get_error_hint (json);
    /* Nothing really to verify, merchant says we need to authenticate. */
    break;
  default:
    /* unexpected response code */
    wgr.hr.ec = TALER_JSON_get_error_code (json);
    wgr.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) wgr.hr.ec);
    break;
  }
  gpwh->cb (gpwh->cb_cls,
            &wgr);
  TALER_MERCHANT_get_private_webhooks_cancel (gpwh);
}


struct TALER_MERCHANT_GetPrivateWebhooksHandle *
TALER_MERCHANT_get_private_webhooks_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url)
{
  struct TALER_MERCHANT_GetPrivateWebhooksHandle *gpwh;

  gpwh = GNUNET_new (struct TALER_MERCHANT_GetPrivateWebhooksHandle);
  gpwh->ctx = ctx;
  gpwh->base_url = GNUNET_strdup (url);
  return gpwh;
}


enum TALER_ErrorCode
TALER_MERCHANT_get_private_webhooks_start (
  struct TALER_MERCHANT_GetPrivateWebhooksHandle *gpwh,
  TALER_MERCHANT_GetPrivateWebhooksCallback cb,
  TALER_MERCHANT_GET_PRIVATE_WEBHOOKS_RESULT_CLOSURE *cb_cls)
{
  CURL *eh;

  gpwh->cb = cb;
  gpwh->cb_cls = cb_cls;
  gpwh->url = TALER_url_join (gpwh->base_url,
                              "private/webhooks",
                              NULL);
  if (NULL == gpwh->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  eh = TALER_MERCHANT_curl_easy_get_ (gpwh->url);
  if (NULL == eh)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  gpwh->job = GNUNET_CURL_job_add (gpwh->ctx,
                                   eh,
                                   &handle_get_webhooks_finished,
                                   gpwh);
  if (NULL == gpwh->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_MERCHANT_get_private_webhooks_cancel (
  struct TALER_MERCHANT_GetPrivateWebhooksHandle *gpwh)
{
  if (NULL != gpwh->job)
  {
    GNUNET_CURL_job_cancel (gpwh->job);
    gpwh->job = NULL;
  }
  GNUNET_free (gpwh->url);
  GNUNET_free (gpwh->base_url);
  GNUNET_free (gpwh);
}


/* end of merchant_api_get-private-webhooks-new.c */
