/*
  This file is part of TALER
  Copyright (C) 2025-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-token.c
 * @brief Implementation of the POST /private/token 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-token.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/token operation.
 */
struct TALER_MERCHANT_PostPrivateTokenHandle
{
  /**
   * 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_PostPrivateTokenCallback cb;

  /**
   * Closure for @a cb.
   */
  TALER_MERCHANT_POST_PRIVATE_TOKEN_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;

  /**
   * Instance identifier (or NULL).
   */
  char *instance_id;

  /**
   * Scope for the token.
   */
  char *scope;

  /**
   * How long the token should be valid.
   */
  struct GNUNET_TIME_Relative duration;

  /**
   * Whether @e duration was explicitly set via options.
   */
  bool duration_set;

  /**
   * Whether the token may be refreshed.
   */
  bool refreshable;

  /**
   * Whether @e refreshable was explicitly set via options.
   */
  bool refreshable_set;

  /**
   * Description for the token (or NULL).
   */
  const char *description;
};


/**
 * Function called when we're done processing the
 * HTTP POST /private/token request.
 *
 * @param cls the `struct TALER_MERCHANT_PostPrivateTokenHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_post_token_finished (void *cls,
                            long response_code,
                            const void *response)
{
  struct TALER_MERCHANT_PostPrivateTokenHandle *ppth = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_PostPrivateTokenResponse ptr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  ppth->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "POST /private/token completed with response code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case MHD_HTTP_OK:
    {
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_string ("access_token",
                                 &ptr.details.ok.access_token),
        GNUNET_JSON_spec_string ("scope",
                                 &ptr.details.ok.scope),
        GNUNET_JSON_spec_bool ("refreshable",
                               &ptr.details.ok.refreshable),
        GNUNET_JSON_spec_timestamp ("expiration",
                                    &ptr.details.ok.expiration),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json,
                             spec,
                             NULL,
                             NULL))
      {
        GNUNET_break_op (0);
        ptr.hr.http_status = 0;
        ptr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }
    }
    break;
  case MHD_HTTP_BAD_REQUEST:
    ptr.hr.ec = TALER_JSON_get_error_code (json);
    ptr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_ACCEPTED:
    if (GNUNET_OK !=
        TALER_MERCHANT_parse_mfa_challenge_response_ (
          json,
          &ptr.details.accepted))
    {
      GNUNET_break_op (0);
      ptr.hr.http_status = 0;
      ptr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    }
    break;
  case MHD_HTTP_UNAUTHORIZED:
    ptr.hr.ec = TALER_JSON_get_error_code (json);
    ptr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    ptr.hr.ec = TALER_JSON_get_error_code (json);
    ptr.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) ptr.hr.ec);
    break;
  }
  ppth->cb (ppth->cb_cls,
            &ptr);
  if (MHD_HTTP_ACCEPTED == response_code)
    TALER_MERCHANT_mfa_challenge_response_free (
      &ptr.details.accepted);
  TALER_MERCHANT_post_private_token_cancel (ppth);
}


struct TALER_MERCHANT_PostPrivateTokenHandle *
TALER_MERCHANT_post_private_token_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const char *instance_id,
  const char *scope)
{
  struct TALER_MERCHANT_PostPrivateTokenHandle *ppth;

  ppth = GNUNET_new (struct TALER_MERCHANT_PostPrivateTokenHandle);
  ppth->ctx = ctx;
  ppth->base_url = GNUNET_strdup (url);
  if (NULL != instance_id)
    ppth->instance_id = GNUNET_strdup (instance_id);
  ppth->scope = GNUNET_strdup (scope);
  return ppth;
}


enum GNUNET_GenericReturnValue
TALER_MERCHANT_post_private_token_set_options_ (
  struct TALER_MERCHANT_PostPrivateTokenHandle *ppth,
  unsigned int num_options,
  const struct TALER_MERCHANT_PostPrivateTokenOptionValue *options)
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    switch (options[i].option)
    {
    case TALER_MERCHANT_POST_PRIVATE_TOKEN_OPTION_END:
      return GNUNET_OK;
    case TALER_MERCHANT_POST_PRIVATE_TOKEN_OPTION_DURATION:
      ppth->duration = options[i].details.duration;
      ppth->duration_set = true;
      break;
    case TALER_MERCHANT_POST_PRIVATE_TOKEN_OPTION_REFRESHABLE:
      ppth->refreshable = options[i].details.refreshable;
      ppth->refreshable_set = true;
      break;
    case TALER_MERCHANT_POST_PRIVATE_TOKEN_OPTION_DESCRIPTION:
      ppth->description = options[i].details.description;
      break;
    default:
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_MERCHANT_post_private_token_start (
  struct TALER_MERCHANT_PostPrivateTokenHandle *ppth,
  TALER_MERCHANT_PostPrivateTokenCallback cb,
  TALER_MERCHANT_POST_PRIVATE_TOKEN_RESULT_CLOSURE *cb_cls)
{
  json_t *req_obj;
  CURL *eh;

  ppth->cb = cb;
  ppth->cb_cls = cb_cls;
  if (NULL != ppth->instance_id)
  {
    char *path;

    GNUNET_asprintf (&path,
                     "instances/%s/private/token",
                     ppth->instance_id);
    ppth->url = TALER_url_join (ppth->base_url,
                                path,
                                NULL);
    GNUNET_free (path);
  }
  else
  {
    ppth->url = TALER_url_join (ppth->base_url,
                                "private/token",
                                NULL);
  }
  if (NULL == ppth->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  req_obj = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_string ("scope",
                             ppth->scope));
  if (ppth->duration_set)
  {
    GNUNET_assert (0 ==
                   json_object_set_new (req_obj,
                                        "duration",
                                        GNUNET_JSON_from_time_rel (
                                          ppth->duration)));
  }
  if (ppth->refreshable_set)
  {
    GNUNET_assert (0 ==
                   json_object_set_new (req_obj,
                                        "refreshable",
                                        json_boolean (ppth->refreshable)));
  }
  if (NULL != ppth->description)
  {
    GNUNET_assert (0 ==
                   json_object_set_new (req_obj,
                                        "description",
                                        json_string (ppth->description)));
  }
  eh = TALER_MERCHANT_curl_easy_get_ (ppth->url);
  if ( (NULL == eh) ||
       (GNUNET_OK !=
        TALER_curl_easy_post (&ppth->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_POST));
  ppth->job = GNUNET_CURL_job_add2 (ppth->ctx,
                                    eh,
                                    ppth->post_ctx.headers,
                                    &handle_post_token_finished,
                                    ppth);
  if (NULL == ppth->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_MERCHANT_post_private_token_cancel (
  struct TALER_MERCHANT_PostPrivateTokenHandle *ppth)
{
  if (NULL != ppth->job)
  {
    GNUNET_CURL_job_cancel (ppth->job);
    ppth->job = NULL;
  }
  TALER_curl_easy_post_finished (&ppth->post_ctx);
  GNUNET_free (ppth->instance_id);
  GNUNET_free (ppth->scope);
  GNUNET_free (ppth->url);
  GNUNET_free (ppth->base_url);
  GNUNET_free (ppth);
}


/* end of merchant_api_post-private-token.c */
