/*
  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-otp-devices-DEVICE_ID.c
 * @brief Implementation of the GET /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/get-private-otp-devices-DEVICE_ID.h>
#include "merchant_api_curl_defaults.h"
#include <taler/taler_json_lib.h>


/**
 * Handle for a GET /private/otp-devices/$DEVICE_ID operation.
 */
struct TALER_MERCHANT_GetPrivateOtpDeviceHandle
{
  /**
   * Base URL of the merchant backend.
   */
  char *base_url;

  /**
   * OTP device identifier.
   */
  char *otp_device_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_GetPrivateOtpDeviceCallback cb;

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

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

  /**
   * Fake time for OTP code computation.
   */
  struct GNUNET_TIME_Timestamp faketime;

  /**
   * Price amount for OTP code computation.
   */
  struct TALER_Amount price;

  /**
   * True if @e faketime was explicitly set via options.
   */
  bool have_faketime;

  /**
   * True if @e price was explicitly set via options.
   */
  bool have_price;
};


/**
 * Function called when we're done processing the
 * HTTP GET /private/otp-devices/$DEVICE_ID request.
 *
 * @param cls the `struct TALER_MERCHANT_GetPrivateOtpDeviceHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_get_otp_device_finished (void *cls,
                                long response_code,
                                const void *response)
{
  struct TALER_MERCHANT_GetPrivateOtpDeviceHandle *god = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_GetPrivateOtpDeviceResponse ogr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  god->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Got /private/otp-devices/$DEVICE_ID response with status code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case MHD_HTTP_OK:
    {
      uint32_t alg32;
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_string ("device_description",
                                 &ogr.details.ok.otp_device_description),
        GNUNET_JSON_spec_uint32 ("otp_algorithm",
                                 &alg32),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_uint64 ("otp_ctr",
                                   &ogr.details.ok.otp_ctr),
          NULL),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_uint64 ("otp_timestamp",
                                   &ogr.details.ok.otp_timestamp_s),
          NULL),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_string ("otp_code",
                                   &ogr.details.ok.otp_code),
          NULL),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK ==
          GNUNET_JSON_parse (json,
                             spec,
                             NULL, NULL))
      {
        ogr.details.ok.otp_alg =
          (enum TALER_MerchantConfirmationAlgorithm) alg32;
        god->cb (god->cb_cls,
                 &ogr);
        TALER_MERCHANT_get_private_otp_device_cancel (god);
        return;
      }
      ogr.hr.http_status = 0;
      ogr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
      break;
    }
  case MHD_HTTP_UNAUTHORIZED:
    ogr.hr.ec = TALER_JSON_get_error_code (json);
    ogr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_NOT_FOUND:
    ogr.hr.ec = TALER_JSON_get_error_code (json);
    ogr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    ogr.hr.ec = TALER_JSON_get_error_code (json);
    ogr.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) ogr.hr.ec);
    break;
  }
  god->cb (god->cb_cls,
           &ogr);
  TALER_MERCHANT_get_private_otp_device_cancel (god);
}


struct TALER_MERCHANT_GetPrivateOtpDeviceHandle *
TALER_MERCHANT_get_private_otp_device_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const char *otp_device_id)
{
  struct TALER_MERCHANT_GetPrivateOtpDeviceHandle *god;

  god = GNUNET_new (struct TALER_MERCHANT_GetPrivateOtpDeviceHandle);
  god->ctx = ctx;
  god->base_url = GNUNET_strdup (url);
  god->otp_device_id = GNUNET_strdup (otp_device_id);
  return god;
}


enum GNUNET_GenericReturnValue
TALER_MERCHANT_get_private_otp_device_set_options_ (
  struct TALER_MERCHANT_GetPrivateOtpDeviceHandle *god,
  unsigned int num_options,
  const struct TALER_MERCHANT_GetPrivateOtpDeviceOptionValue *options)
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    switch (options[i].option)
    {
    case TALER_MERCHANT_GET_PRIVATE_OTP_DEVICE_OPTION_END:
      return GNUNET_OK;
    case TALER_MERCHANT_GET_PRIVATE_OTP_DEVICE_OPTION_FAKETIME:
      god->faketime = options[i].details.faketime;
      god->have_faketime = true;
      break;
    case TALER_MERCHANT_GET_PRIVATE_OTP_DEVICE_OPTION_PRICE:
      god->price = options[i].details.price;
      god->have_price = true;
      break;
    default:
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_MERCHANT_get_private_otp_device_start (
  struct TALER_MERCHANT_GetPrivateOtpDeviceHandle *god,
  TALER_MERCHANT_GetPrivateOtpDeviceCallback cb,
  TALER_MERCHANT_GET_PRIVATE_OTP_DEVICE_RESULT_CLOSURE *cb_cls)
{
  CURL *eh;

  god->cb = cb;
  god->cb_cls = cb_cls;
  {
    char *path;
    char faketime_s[24];

    GNUNET_asprintf (&path,
                     "private/otp-devices/%s",
                     god->otp_device_id);
    if (god->have_faketime)
      GNUNET_snprintf (faketime_s,
                       sizeof (faketime_s),
                       "%llu",
                       (unsigned long long)
                       GNUNET_TIME_timestamp_to_s (god->faketime));
    god->url = TALER_url_join (god->base_url,
                               path,
                               god->have_faketime
                               ? "faketime"
                               : NULL,
                               god->have_faketime
                               ? faketime_s
                               : NULL,
                               god->have_price
                               ? "price"
                               : NULL,
                               god->have_price
                               ? TALER_amount2s (&god->price)
                               : NULL,
                               NULL);
    GNUNET_free (path);
  }
  if (NULL == god->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  eh = TALER_MERCHANT_curl_easy_get_ (god->url);
  if (NULL == eh)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  god->job = GNUNET_CURL_job_add (god->ctx,
                                  eh,
                                  &handle_get_otp_device_finished,
                                  god);
  if (NULL == god->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_MERCHANT_get_private_otp_device_cancel (
  struct TALER_MERCHANT_GetPrivateOtpDeviceHandle *god)
{
  if (NULL != god->job)
  {
    GNUNET_CURL_job_cancel (god->job);
    god->job = NULL;
  }
  GNUNET_free (god->url);
  GNUNET_free (god->otp_device_id);
  GNUNET_free (god->base_url);
  GNUNET_free (god);
}


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