/*
  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-templates-TEMPLATE_ID.c
 * @brief Implementation of the GET /private/templates/$TEMPLATE_ID 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-templates-TEMPLATE_ID.h>
#include "merchant_api_curl_defaults.h"
#include <taler/taler_json_lib.h>


/**
 * Handle for a GET /private/templates/$TEMPLATE_ID operation.
 */
struct TALER_MERCHANT_GetPrivateTemplateHandle
{
  /**
   * Base URL of the merchant backend.
   */
  char *base_url;

  /**
   * Template identifier.
   */
  char *template_id;

  /**
   * 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_GetPrivateTemplateCallback cb;

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

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


/**
 * Function called when we're done processing the
 * HTTP GET /private/templates/$TEMPLATE_ID request.
 *
 * @param cls the `struct TALER_MERCHANT_GetPrivateTemplateHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_get_template_finished (void *cls,
                              long response_code,
                              const void *response)
{
  struct TALER_MERCHANT_GetPrivateTemplateHandle *gpt = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_GetPrivateTemplateResponse tgr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  gpt->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Got /private/templates/$TEMPLATE_ID response with status code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case MHD_HTTP_OK:
    {
      const json_t *contract;
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_string ("template_description",
                                 &tgr.details.ok.template_description),
        GNUNET_JSON_spec_mark_optional (
          TALER_JSON_spec_slug ("otp_id",
                                &tgr.details.ok.otp_id),
          NULL),
        GNUNET_JSON_spec_object_const ("template_contract",
                                       &contract),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_object_const ("editable_defaults",
                                         &tgr.details.ok.editable_defaults),
          NULL),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_string ("required_currency",
                                   &tgr.details.ok.required_currency),
          NULL),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK ==
          GNUNET_JSON_parse (json,
                             spec,
                             NULL, NULL))
      {
        tgr.details.ok.template_contract = contract;
        gpt->cb (gpt->cb_cls,
                 &tgr);
        TALER_MERCHANT_get_private_template_cancel (gpt);
        return;
      }
      tgr.hr.http_status = 0;
      tgr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
      break;
    }
  case MHD_HTTP_UNAUTHORIZED:
    tgr.hr.ec = TALER_JSON_get_error_code (json);
    tgr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_NOT_FOUND:
    tgr.hr.ec = TALER_JSON_get_error_code (json);
    tgr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    tgr.hr.ec = TALER_JSON_get_error_code (json);
    tgr.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) tgr.hr.ec);
    break;
  }
  gpt->cb (gpt->cb_cls,
           &tgr);
  TALER_MERCHANT_get_private_template_cancel (gpt);
}


struct TALER_MERCHANT_GetPrivateTemplateHandle *
TALER_MERCHANT_get_private_template_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const char *template_id)
{
  struct TALER_MERCHANT_GetPrivateTemplateHandle *gpt;

  gpt = GNUNET_new (struct TALER_MERCHANT_GetPrivateTemplateHandle);
  gpt->ctx = ctx;
  gpt->base_url = GNUNET_strdup (url);
  gpt->template_id = GNUNET_strdup (template_id);
  return gpt;
}


enum TALER_ErrorCode
TALER_MERCHANT_get_private_template_start (
  struct TALER_MERCHANT_GetPrivateTemplateHandle *gpt,
  TALER_MERCHANT_GetPrivateTemplateCallback cb,
  TALER_MERCHANT_GET_PRIVATE_TEMPLATE_RESULT_CLOSURE *cb_cls)
{
  CURL *eh;

  gpt->cb = cb;
  gpt->cb_cls = cb_cls;
  {
    char *path;

    GNUNET_asprintf (&path,
                     "private/templates/%s",
                     gpt->template_id);
    gpt->url = TALER_url_join (gpt->base_url,
                               path,
                               NULL);
    GNUNET_free (path);
  }
  if (NULL == gpt->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  eh = TALER_MERCHANT_curl_easy_get_ (gpt->url);
  if (NULL == eh)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  gpt->job = GNUNET_CURL_job_add (gpt->ctx,
                                  eh,
                                  &handle_get_template_finished,
                                  gpt);
  if (NULL == gpt->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_MERCHANT_get_private_template_cancel (
  struct TALER_MERCHANT_GetPrivateTemplateHandle *gpt)
{
  if (NULL != gpt->job)
  {
    GNUNET_CURL_job_cancel (gpt->job);
    gpt->job = NULL;
  }
  GNUNET_free (gpt->url);
  GNUNET_free (gpt->template_id);
  GNUNET_free (gpt->base_url);
  GNUNET_free (gpt);
}


/* end of merchant_api_get-private-templates-TEMPLATE_ID-new.c */
