/*
  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_patch-private-otp-devices-DEVICE_ID.c
 * @brief Implementation of the PATCH /private/otp-devices/$DEVICE_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/patch-private-otp-devices-DEVICE_ID.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 PATCH /private/otp-devices/$DEVICE_ID operation.
 */
struct TALER_MERCHANT_PatchPrivateOtpDeviceHandle
{
  /**
   * 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_PatchPrivateOtpDeviceCallback cb;

  /**
   * Closure for @a cb.
   */
  TALER_MERCHANT_PATCH_PRIVATE_OTP_DEVICE_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 to keep unchanged.
   */
  char *otp_key;

  /**
   * OTP algorithm.
   */
  enum TALER_MerchantConfirmationAlgorithm mca;

  /**
   * 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 PATCH /private/otp-devices/$DEVICE_ID request.
 *
 * @param cls the `struct TALER_MERCHANT_PatchPrivateOtpDeviceHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_patch_otp_device_finished (void *cls,
                                  long response_code,
                                  const void *response)
{
  struct TALER_MERCHANT_PatchPrivateOtpDeviceHandle *odh = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_PatchPrivateOtpDeviceResponse odr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  odh->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "PATCH /private/otp-devices/$DEVICE_ID 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);
    GNUNET_break_op (0);
    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_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;
  }
  odh->cb (odh->cb_cls,
           &odr);
  TALER_MERCHANT_patch_private_otp_device_cancel (odh);
}


struct TALER_MERCHANT_PatchPrivateOtpDeviceHandle *
TALER_MERCHANT_patch_private_otp_device_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 mca)
{
  struct TALER_MERCHANT_PatchPrivateOtpDeviceHandle *odh;

  odh = GNUNET_new (struct TALER_MERCHANT_PatchPrivateOtpDeviceHandle);
  odh->ctx = ctx;
  odh->base_url = GNUNET_strdup (url);
  odh->otp_device_id = GNUNET_strdup (otp_device_id);
  odh->otp_device_description = GNUNET_strdup (otp_device_description);
  if (NULL != otp_key)
    odh->otp_key = GNUNET_strdup (otp_key);
  odh->mca = mca;
  return odh;
}


enum GNUNET_GenericReturnValue
TALER_MERCHANT_patch_private_otp_device_set_options_ (
  struct TALER_MERCHANT_PatchPrivateOtpDeviceHandle *odh,
  unsigned int num_options,
  const struct TALER_MERCHANT_PatchPrivateOtpDeviceOptionValue *options)
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    switch (options[i].option)
    {
    case TALER_MERCHANT_PATCH_PRIVATE_OTP_DEVICE_OPTION_END:
      return GNUNET_OK;
    case TALER_MERCHANT_PATCH_PRIVATE_OTP_DEVICE_OPTION_OTP_CTR:
      odh->otp_ctr = options[i].details.otp_ctr;
      odh->have_otp_ctr = true;
      break;
    default:
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_MERCHANT_patch_private_otp_device_start (
  struct TALER_MERCHANT_PatchPrivateOtpDeviceHandle *odh,
  TALER_MERCHANT_PatchPrivateOtpDeviceCallback cb,
  TALER_MERCHANT_PATCH_PRIVATE_OTP_DEVICE_RESULT_CLOSURE *cb_cls)
{
  json_t *req_obj;
  CURL *eh;

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

    GNUNET_asprintf (&path,
                     "private/otp-devices/%s",
                     odh->otp_device_id);
    odh->url = TALER_url_join (odh->base_url,
                               path,
                               NULL);
    GNUNET_free (path);
  }
  if (NULL == odh->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  req_obj = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_string ("otp_device_description",
                             odh->otp_device_description),
    GNUNET_JSON_pack_uint64 ("otp_algorithm",
                             (uint32_t) odh->mca),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_string ("otp_key",
                               odh->otp_key)));
  if (odh->have_otp_ctr)
  {
    GNUNET_assert (
      0 ==
      json_object_set_new (req_obj,
                           "otp_ctr",
                           json_integer ((json_int_t) odh->otp_ctr)));
  }
  eh = TALER_MERCHANT_curl_easy_get_ (odh->url);
  if ( (NULL == eh) ||
       (GNUNET_OK !=
        TALER_curl_easy_post (&odh->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);
  GNUNET_assert (CURLE_OK ==
                 curl_easy_setopt (eh,
                                   CURLOPT_CUSTOMREQUEST,
                                   MHD_HTTP_METHOD_PATCH));
  odh->job = GNUNET_CURL_job_add2 (odh->ctx,
                                   eh,
                                   odh->post_ctx.headers,
                                   &handle_patch_otp_device_finished,
                                   odh);
  if (NULL == odh->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


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


/* end of merchant_api_patch-private-otp-devices-DEVICE_ID-new.c */
