/*
  This file is part of TALER
  Copyright (C) 2014-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-management-instances-INSTANCE-auth.c
 * @brief Implementation of the POST /management/instances/$INSTANCE/auth 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-management-instances-INSTANCE-auth.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 /management/instances/$INSTANCE/auth operation.
 */
struct TALER_MERCHANT_PostManagementInstancesAuthHandle
{
  /**
   * 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_PostManagementInstancesAuthCallback cb;

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

  /**
   * New authentication password.
   */
  char *auth_password;
};


/**
 * Function called when we're done processing the
 * HTTP POST /management/instances/$INSTANCE/auth request.
 *
 * @param cls the `struct TALER_MERCHANT_PostManagementInstancesAuthHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_post_management_instances_auth_finished (void *cls,
                                                long response_code,
                                                const void *response)
{
  struct TALER_MERCHANT_PostManagementInstancesAuthHandle *piah = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_PostManagementInstancesAuthResponse iar = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  piah->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "POST /management/instances/$INSTANCE/auth completed with "
              "response code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case MHD_HTTP_NO_CONTENT:
    break;
  case MHD_HTTP_ACCEPTED:
    if (GNUNET_OK !=
        TALER_MERCHANT_parse_mfa_challenge_response_ (
          json,
          &iar.details.accepted))
    {
      GNUNET_break_op (0);
      iar.hr.http_status = 0;
      iar.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    }
    break;
  case MHD_HTTP_BAD_REQUEST:
    iar.hr.ec = TALER_JSON_get_error_code (json);
    iar.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_UNAUTHORIZED:
    iar.hr.ec = TALER_JSON_get_error_code (json);
    iar.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  default:
    iar.hr.ec = TALER_JSON_get_error_code (json);
    iar.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) iar.hr.ec);
    break;
  }
  piah->cb (piah->cb_cls,
            &iar);
  if (MHD_HTTP_ACCEPTED == response_code)
    TALER_MERCHANT_mfa_challenge_response_free (
      &iar.details.accepted);
  TALER_MERCHANT_post_management_instances_auth_cancel (piah);
}


struct TALER_MERCHANT_PostManagementInstancesAuthHandle *
TALER_MERCHANT_post_management_instances_auth_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const char *instance_id)
{
  struct TALER_MERCHANT_PostManagementInstancesAuthHandle *piah;

  piah = GNUNET_new (struct TALER_MERCHANT_PostManagementInstancesAuthHandle);
  piah->ctx = ctx;
  piah->base_url = GNUNET_strdup (url);
  if (NULL != instance_id)
    piah->instance_id = GNUNET_strdup (instance_id);
  return piah;
}


void
TALER_MERCHANT_post_management_instances_auth_set_options_ (
  struct TALER_MERCHANT_PostManagementInstancesAuthHandle *piah,
  unsigned int num_options,
  const struct TALER_MERCHANT_PostManagementInstancesAuthOptionValue options[])
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    switch (options[i].option)
    {
    case TALER_MERCHANT_POST_MANAGEMENT_INSTANCES_AUTH_OPTION_END:
      return;
    case TALER_MERCHANT_POST_MANAGEMENT_INSTANCES_AUTH_OPTION_PASSWORD:
      GNUNET_free (piah->auth_password);
      if (NULL != options[i].details.password)
        piah->auth_password = GNUNET_strdup (
          options[i].details.password);
      break;
    }
  }
}


enum TALER_ErrorCode
TALER_MERCHANT_post_management_instances_auth_start (
  struct TALER_MERCHANT_PostManagementInstancesAuthHandle *piah,
  TALER_MERCHANT_PostManagementInstancesAuthCallback cb,
  TALER_MERCHANT_POST_MANAGEMENT_INSTANCES_AUTH_RESULT_CLOSURE *cb_cls)
{
  json_t *req_obj;
  CURL *eh;

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

    GNUNET_asprintf (&path,
                     "management/instances/%s/auth",
                     piah->instance_id);
    piah->url = TALER_url_join (piah->base_url,
                                path,
                                NULL);
    GNUNET_free (path);
  }
  else
  {
    /* backend_url is already identifying the instance */
    piah->url = TALER_url_join (piah->base_url,
                                "private/auth",
                                NULL);
  }
  if (NULL == piah->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;

  if (NULL == piah->auth_password)
  {
    req_obj = GNUNET_JSON_PACK (
      GNUNET_JSON_pack_string ("method",
                               "external"));
  }
  else
  {
    req_obj = GNUNET_JSON_PACK (
      GNUNET_JSON_pack_string ("method",
                               "token"),
      GNUNET_JSON_pack_string ("password",
                               piah->auth_password));
  }
  eh = TALER_MERCHANT_curl_easy_get_ (piah->url);
  if ( (NULL == eh) ||
       (GNUNET_OK !=
        TALER_curl_easy_post (&piah->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));
  piah->job = GNUNET_CURL_job_add2 (piah->ctx,
                                    eh,
                                    piah->post_ctx.headers,
                                    &
                                    handle_post_management_instances_auth_finished,
                                    piah);
  if (NULL == piah->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_MERCHANT_post_management_instances_auth_cancel (
  struct TALER_MERCHANT_PostManagementInstancesAuthHandle *piah)
{
  if (NULL != piah->job)
  {
    GNUNET_CURL_job_cancel (piah->job);
    piah->job = NULL;
  }
  TALER_curl_easy_post_finished (&piah->post_ctx);
  GNUNET_free (piah->instance_id);
  GNUNET_free (piah->auth_password);
  GNUNET_free (piah->url);
  GNUNET_free (piah->base_url);
  GNUNET_free (piah);
}


/* end of merchant_api_post-management-instances-INSTANCE-auth-new.c */
