/*
  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_post-private-otp-devices.c
 * @brief Implementation of the POST /private/otp-devices 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/post-private-otp-devices.h>
#include "merchant_api_curl_defaults.h"
#include "merchant_api_common.h"
#include <taler/taler_json_lib.h>
#include <taler/taler_curl_lib.h>


/**
 * Handle for a POST /private/otp-devices operation.
 */
struct TALER_MERCHANT_PostPrivateOtpDevicesHandle
{
  /**
   * 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_PostPrivateOtpDevicesCallback cb;

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

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

  /**
   * Minor context that holds body and headers.
   */
  struct TALER_CURL_PostContext post_ctx;

  /**
   * OTP device identifier.
   */
  char *otp_device_id;

  /**
   * Human-readable description.
   */
  char *otp_device_description;

  /**
   * Base32-encoded OTP secret key (or NULL).
   */
  char *otp_key;

  /**
   * OTP algorithm to use.
   */
  enum TALER_MerchantConfirmationAlgorithm otp_algorithm;

  /**
   * Initial counter value (for HOTP).
   */
  uint64_t otp_ctr;

  /**
   * True if @e otp_ctr was explicitly set via options.
   */
  bool have_otp_ctr;
};


/**
 * Function called when we're done processing the
 * HTTP POST /private/otp-devices request.
 *
 * @param cls the `struct TALER_MERCHANT_PostPrivateOtpDevicesHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_post_otp_devices_finished (void *cls,
                                  long response_code,
                                  const void *response)
{
  struct TALER_MERCHANT_PostPrivateOtpDevicesHandle *ppoh = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_PostPrivateOtpDevicesResponse odr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  ppoh->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "POST /private/otp-devices completed with response code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case 0:
    odr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_NO_CONTENT:
    break;
  case MHD_HTTP_BAD_REQUEST:
    odr.hr.ec = TALER_JSON_get_error_code (json);
    odr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_UNAUTHORIZED:
    odr.hr.ec = TALER_JSON_get_error_code (json);
    odr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_FORBIDDEN:
    odr.hr.ec = TALER_JSON_get_error_code (json);
    odr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_NOT_FOUND:
    odr.hr.ec = TALER_JSON_get_error_code (json);
    odr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_CONFLICT:
    odr.hr.ec = TALER_JSON_get_error_code (json);
    odr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    odr.hr.ec = TALER_JSON_get_error_code (json);
    odr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    TALER_MERCHANT_parse_error_details_ (json,
                                         response_code,
                                         &odr.hr);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d\n",
                (unsigned int) response_code,
                (int) odr.hr.ec);
    GNUNET_break_op (0);
    break;
  }
  ppoh->cb (ppoh->cb_cls,
            &odr);
  TALER_MERCHANT_post_private_otp_devices_cancel (ppoh);
}


struct TALER_MERCHANT_PostPrivateOtpDevicesHandle *
TALER_MERCHANT_post_private_otp_devices_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const char *otp_device_id,
  const char *otp_device_description,
  const char *otp_key,
  enum TALER_MerchantConfirmationAlgorithm otp_algorithm)
{
  struct TALER_MERCHANT_PostPrivateOtpDevicesHandle *ppoh;

  ppoh = GNUNET_new (struct TALER_MERCHANT_PostPrivateOtpDevicesHandle);
  ppoh->ctx = ctx;
  ppoh->base_url = GNUNET_strdup (url);
  ppoh->otp_device_id = GNUNET_strdup (otp_device_id);
  ppoh->otp_device_description = GNUNET_strdup (otp_device_description);
  if (NULL != otp_key)
    ppoh->otp_key = GNUNET_strdup (otp_key);
  ppoh->otp_algorithm = otp_algorithm;
  return ppoh;
}


enum GNUNET_GenericReturnValue
TALER_MERCHANT_post_private_otp_devices_set_options_ (
  struct TALER_MERCHANT_PostPrivateOtpDevicesHandle *ppoh,
  unsigned int num_options,
  const struct TALER_MERCHANT_PostPrivateOtpDevicesOptionValue *options)
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    switch (options[i].option)
    {
    case TALER_MERCHANT_POST_PRIVATE_OTP_DEVICES_OPTION_END:
      return GNUNET_OK;
    case TALER_MERCHANT_POST_PRIVATE_OTP_DEVICES_OPTION_OTP_CTR:
      ppoh->otp_ctr = options[i].details.otp_ctr;
      ppoh->have_otp_ctr = true;
      break;
    default:
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_MERCHANT_post_private_otp_devices_start (
  struct TALER_MERCHANT_PostPrivateOtpDevicesHandle *ppoh,
  TALER_MERCHANT_PostPrivateOtpDevicesCallback cb,
  TALER_MERCHANT_POST_PRIVATE_OTP_DEVICES_RESULT_CLOSURE *cb_cls)
{
  json_t *req_obj;
  CURL *eh;

  ppoh->cb = cb;
  ppoh->cb_cls = cb_cls;
  ppoh->url = TALER_url_join (ppoh->base_url,
                              "private/otp-devices",
                              NULL);
  if (NULL == ppoh->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  req_obj = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_string ("otp_device_id",
                             ppoh->otp_device_id),
    GNUNET_JSON_pack_string ("otp_device_description",
                             ppoh->otp_device_description),
    GNUNET_JSON_pack_uint64 ("otp_algorithm",
                             (uint32_t) ppoh->otp_algorithm),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_string ("otp_key",
                               ppoh->otp_key)),
    GNUNET_JSON_pack_uint64 ("otp_ctr",
                             ppoh->otp_ctr));
  eh = TALER_MERCHANT_curl_easy_get_ (ppoh->url);
  if ( (NULL == eh) ||
       (GNUNET_OK !=
        TALER_curl_easy_post (&ppoh->post_ctx,
                              eh,
                              req_obj)) )
  {
    GNUNET_break (0);
    json_decref (req_obj);
    if (NULL != eh)
      curl_easy_cleanup (eh);
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  json_decref (req_obj);
  ppoh->job = GNUNET_CURL_job_add2 (ppoh->ctx,
                                    eh,
                                    ppoh->post_ctx.headers,
                                    &handle_post_otp_devices_finished,
                                    ppoh);
  if (NULL == ppoh->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_MERCHANT_post_private_otp_devices_cancel (
  struct TALER_MERCHANT_PostPrivateOtpDevicesHandle *ppoh)
{
  if (NULL != ppoh->job)
  {
    GNUNET_CURL_job_cancel (ppoh->job);
    ppoh->job = NULL;
  }
  TALER_curl_easy_post_finished (&ppoh->post_ctx);
  GNUNET_free (ppoh->otp_device_id);
  GNUNET_free (ppoh->otp_device_description);
  GNUNET_free (ppoh->otp_key);
  GNUNET_free (ppoh->url);
  GNUNET_free (ppoh->base_url);
  GNUNET_free (ppoh);
}


/* end of merchant_api_post-private-otp-devices-new.c */
