/*
  This file is part of TALER
  Copyright (C) 2026 Taler Systems SA

  TALER is free software; you can redistribute it and/or modify it under the
  terms of the GNU General Public License as published by the Free Software
  Foundation; either version 3, 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 General Public License for more details.

  You should have received a copy of the GNU General Public License along with
  TALER; see the file COPYING.  If not, see
  <http://www.gnu.org/licenses/>
*/
/**
 * @file bank-lib/bank_api_registration.c
 * @brief Implementation of the POST /registration request of the bank's HTTP API
 * @author Christian Grothoff
 */
#include "bank_api_common.h"
#include <microhttpd.h> /* just for HTTP status codes */
#include "taler/taler_json_lib.h"
#include "taler/taler_signatures.h"
#include "taler/taler_curl_lib.h"


/**
 * @brief A /registration Handle
 */
struct TALER_BANK_RegistrationHandle
{

  /**
   * The URL for this request.
   */
  char *request_url;

  /**
   * POST context.
   */
  struct TALER_CURL_PostContext post_ctx;

  /**
   * Handle for the request.
   */
  struct GNUNET_CURL_Job *job;

  /**
   * Function to call with the result.
   */
  TALER_BANK_RegistrationCallback cb;

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

};


/**
 * Parse the "subject" field of a successful /registration response.
 * The field is a JSON object discriminated by "type".
 *
 * @param subject_json the JSON object to parse (the inner "subject" value)
 * @param[out] ts set to the parsed transfer subject on success
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
 */
static enum GNUNET_GenericReturnValue
parse_transfer_subject (const json_t *subject_json,
                        struct TALER_BANK_TransferSubject *ts)
{
  const char *type_str;
  struct GNUNET_JSON_Specification type_spec[] = {
    GNUNET_JSON_spec_string ("type",
                             &type_str),
    GNUNET_JSON_spec_end ()
  };

  if (GNUNET_OK !=
      GNUNET_JSON_parse (subject_json,
                         type_spec,
                         NULL,
                         NULL))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }

  if (0 == strcasecmp (type_str,
                       "SIMPLE"))
  {
    struct GNUNET_JSON_Specification spec[] = {
      TALER_JSON_spec_amount_any (
        "credit_amount",
        &ts->details.simple.credit_amount),
      GNUNET_JSON_spec_string (
        "subject",
        (const char **) &ts->details.simple.subject),
      GNUNET_JSON_spec_end ()
    };

    if (GNUNET_OK !=
        GNUNET_JSON_parse (subject_json,
                           spec,
                           NULL, NULL))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    ts->format = TALER_BANK_SUBJECT_FORMAT_SIMPLE;
    return GNUNET_OK;
  }
  if (0 == strcasecmp (type_str,
                       "URI"))
  {
    struct GNUNET_JSON_Specification spec[] = {
      GNUNET_JSON_spec_string (
        "uri",
        (const char **) &ts->details.uri.uri),
      GNUNET_JSON_spec_end ()
    };

    if (GNUNET_OK !=
        GNUNET_JSON_parse (subject_json,
                           spec,
                           NULL, NULL))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    ts->format = TALER_BANK_SUBJECT_FORMAT_URI;
    return GNUNET_OK;
  }
  if (0 == strcasecmp (type_str,
                       "CH_QR_BILL"))
  {
    struct GNUNET_JSON_Specification spec[] = {
      TALER_JSON_spec_amount_any (
        "credit_amount",
        &ts->details.ch_qr_bill.credit_amount),
      GNUNET_JSON_spec_string (
        "qr_reference_number",
        (const char **) &ts->details.ch_qr_bill.qr_reference_number),
      GNUNET_JSON_spec_end ()
    };

    if (GNUNET_OK !=
        GNUNET_JSON_parse (subject_json,
                           spec,
                           NULL, NULL))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    ts->format = TALER_BANK_SUBJECT_FORMAT_CH_QR_BILL;
    return GNUNET_OK;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
              "Unknown transfer subject type `%s'\n",
              type_str);
  GNUNET_break_op (0);
  return GNUNET_SYSERR;
}


/**
 * Function called when we're done processing the HTTP POST /registration
 * request.
 *
 * @param cls the `struct TALER_BANK_RegistrationHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response parsed JSON result, NULL on error
 */
static void
handle_registration_finished (void *cls,
                              long response_code,
                              const void *response)
{
  struct TALER_BANK_RegistrationHandle *rh = cls;
  const json_t *j = response;
  struct TALER_BANK_RegistrationResponse rr = {
    .http_status = response_code,
    .response = response
  };

  rh->job = NULL;
  switch (response_code)
  {
  case 0:
    rr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_OK:
    {
      const json_t *subjects;
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_array_const ("subjects",
                                      &subjects),
        GNUNET_JSON_spec_timestamp ("expiration",
                                    &rr.details.ok.expiration),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (j,
                             spec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        rr.http_status = 0;
        rr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        break;
      }

      {
        size_t n = json_array_size (subjects);
        struct TALER_BANK_TransferSubject *ts;
        size_t i;
        const json_t *subject;

        ts = GNUNET_new_array (GNUNET_NZL (n),
                               struct TALER_BANK_TransferSubject);
        json_array_foreach ((json_t *) subjects, i, subject)
        {
          if (GNUNET_OK !=
              parse_transfer_subject (subject,
                                      &ts[i]))
          {
            GNUNET_break_op (0);
            rr.http_status = 0;
            rr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
            break;
          }
        }
        if (MHD_HTTP_OK == rr.http_status)
        {
          rr.details.ok.num_subjects = n;
          rr.details.ok.subjects = ts;
          rh->cb (rh->cb_cls,
                  &rr);
          GNUNET_free (ts);
          TALER_BANK_registration_cancel (rh);
          return;
        }
        GNUNET_free (ts);
      }
    }
    break;
  case MHD_HTTP_BAD_REQUEST:
    /* Either we or the service is buggy, or there is an API version conflict. */
    GNUNET_break_op (0);
    rr.ec = TALER_JSON_get_error_code (j);
    break;
  case MHD_HTTP_CONFLICT:
    /* Covers TALER_EC_BANK_DUPLICATE_RESERVE_PUB_SUBJECT,
       TALER_EC_BANK_UNSUPPORTED_SUBJECT_FORMAT,
       TALER_EC_BANK_DERIVATION_REUSE, and
       TALER_EC_BANK_BAD_SIGNATURE. */
    rr.ec = TALER_JSON_get_error_code (j);
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    /* Server had an internal issue; we should retry, but this API
       leaves that to the application. */
    rr.ec = TALER_JSON_get_error_code (j);
    break;
  default:
    /* unexpected response code */
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u\n",
                (unsigned int) response_code);
    GNUNET_break (0);
    rr.ec = TALER_JSON_get_error_code (j);
    break;
  }
  rh->cb (rh->cb_cls,
          &rr);
  TALER_BANK_registration_cancel (rh);
}


struct TALER_BANK_RegistrationHandle *
TALER_BANK_registration (
  struct GNUNET_CURL_Context *ctx,
  const char *base_url,
  const struct TALER_FullPayto *credit_account,
  const struct TALER_Amount *credit_amount,
  enum TALER_BankRegistrationType type,
  const union TALER_AccountPublicKeyP *account_pub,
  const struct TALER_PreparedTransferAuthorizationPrivateKeyP *
  authorization_priv,
  bool recurrent,
  TALER_BANK_RegistrationCallback res_cb,
  void *res_cb_cls)
{
  struct TALER_PreparedTransferAuthorizationPublicKeyP authorization_pub;
  struct TALER_PreparedTransferAuthorizationSignatureP authorization_sig;
  struct TALER_BANK_RegistrationHandle *rh;
  const char *type_str;
  json_t *reg_obj;
  CURL *eh;

  TALER_wallet_prepared_transfer_registration_sign (
    *credit_account,
    credit_amount,
    type,
    recurrent,
    account_pub,
    authorization_priv,
    &authorization_sig);
  GNUNET_CRYPTO_eddsa_key_get_public (&authorization_priv->eddsa_priv,
                                      &authorization_pub.eddsa_pub);

  switch (type)
  {
  case TALER_BANK_REGISTRATION_TYPE_RESERVE:
    type_str = "reserve";
    break;
  case TALER_BANK_REGISTRATION_TYPE_KYC:
    type_str = "kyc";
    break;
  default:
    GNUNET_break (0);
    return NULL;
  }

  reg_obj = GNUNET_JSON_PACK (
    TALER_JSON_pack_full_payto ("credit_account",
                                *credit_account),
    TALER_JSON_pack_amount ("credit_amount",
                            credit_amount),
    GNUNET_JSON_pack_string ("type",
                             type_str),
    GNUNET_JSON_pack_string ("alg",
                             "EdDSA"),
    GNUNET_JSON_pack_data_auto ("account_pub",
                                account_pub),
    GNUNET_JSON_pack_data_auto ("authorization_pub",
                                &authorization_pub),
    GNUNET_JSON_pack_data_auto ("authorization_sig",
                                &authorization_sig),
    GNUNET_JSON_pack_bool ("recurrent",
                           recurrent));
  rh = GNUNET_new (struct TALER_BANK_RegistrationHandle);
  rh->cb = res_cb;
  rh->cb_cls = res_cb_cls;
  rh->request_url = TALER_url_join (base_url,
                                    "registration",
                                    NULL);
  if (NULL == rh->request_url)
  {
    GNUNET_free (rh);
    json_decref (reg_obj);
    return NULL;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Requesting wire transfer subject registration at `%s'\n",
              rh->request_url);
  eh = curl_easy_init ();
  if ( (NULL == eh) ||
       (CURLE_OK !=
        curl_easy_setopt (eh,
                          CURLOPT_URL,
                          rh->request_url)) ||
       (GNUNET_OK !=
        TALER_curl_easy_post (&rh->post_ctx,
                              eh,
                              reg_obj)) )
  {
    GNUNET_break (0);
    TALER_BANK_registration_cancel (rh);
    if (NULL != eh)
      curl_easy_cleanup (eh);
    json_decref (reg_obj);
    return NULL;
  }
  json_decref (reg_obj);
  rh->job = GNUNET_CURL_job_add2 (ctx,
                                  eh,
                                  rh->post_ctx.headers,
                                  &handle_registration_finished,
                                  rh);
  return rh;
}


void
TALER_BANK_registration_cancel (
  struct TALER_BANK_RegistrationHandle *rh)
{
  if (NULL != rh->job)
  {
    GNUNET_CURL_job_cancel (rh->job);
    rh->job = NULL;
  }
  TALER_curl_easy_post_finished (&rh->post_ctx);
  GNUNET_free (rh->request_url);
  GNUNET_free (rh);
}


/* end of bank_api_registration.c */
