/*
  This file is part of TALER
  Copyright (C) 2023, 2024, 2025, 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 lib/exchange_api_get-aml-OFFICER_PUB-attributes-H_NORMALIZED_PAYTO.c
 * @brief Implementation of the /aml/$OFFICER_PUB/attributes request
 * @author Christian Grothoff
 */
#include <microhttpd.h> /* just for HTTP status codes */
#include <gnunet/gnunet_util_lib.h>
#include <gnunet/gnunet_curl_lib.h>
#include "taler/taler_json_lib.h"
#include "exchange_api_handle.h"
#include "taler/taler_signatures.h"
#include "exchange_api_curl_defaults.h"
#include \
  "taler/exchange/get-aml-OFFICER_PUB-attributes-H_NORMALIZED_PAYTO.h"


/**
 * @brief A GET /aml/$OFFICER_PUB/attributes/$H_NORMALIZED_PAYTO Handle
 */
struct TALER_EXCHANGE_GetAmlAttributesHandle
{

  /**
   * Base URL of the exchange.
   */
  char *base_url;

  /**
   * The url for this request.
   */
  char *url;

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

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

  /**
   * Closure for @e cb.
   */
  TALER_EXCHANGE_GET_AML_ATTRIBUTES_RESULT_CLOSURE *cb_cls;

  /**
   * CURL context to use.
   */
  struct GNUNET_CURL_Context *ctx;

  /**
   * Public key of the AML officer (computed from officer_priv in _create).
   */
  struct TALER_AmlOfficerPublicKeyP officer_pub;

  /**
   * Private key of the AML officer (stored for signing in _start).
   */
  struct TALER_AmlOfficerPrivateKeyP officer_priv;

  /**
   * Hash of the normalized payto URI for the account.
   */
  struct TALER_NormalizedPaytoHashP h_payto;

  /**
   * Options set for this request.
   */
  struct
  {
    /**
     * Limit on the number of results (negative = before offset, positive = after).
     * Default: -20.
     */
    int64_t limit;

    /**
     * Row offset threshold. Default: INT64_MAX.
     */
    uint64_t offset;
  } options;

};


/**
 * Parse AML attribute collection events from a JSON array.
 *
 * @param jdetails JSON array with AML attribute collection events
 * @param[out] detail_ar where to write the results
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_attributes (
  const json_t *jdetails,
  struct TALER_EXCHANGE_GetAmlAttributesCollectionEvent *detail_ar)
{
  json_t *obj;
  size_t idx;

  json_array_foreach (jdetails, idx, obj)
  {
    struct TALER_EXCHANGE_GetAmlAttributesCollectionEvent *detail
      = &detail_ar[idx];
    bool by_aml_officer = false;
    struct GNUNET_JSON_Specification spec[] = {
      GNUNET_JSON_spec_uint64 ("rowid",
                               &detail->rowid),
      GNUNET_JSON_spec_bool ("by_aml_officer",
                             &by_aml_officer),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_object_const ("attributes",
                                       &detail->attributes),
        NULL),
      GNUNET_JSON_spec_timestamp ("collection_time",
                                  &detail->collection_time),
      GNUNET_JSON_spec_end ()
    };

    detail->by_aml_officer = false;
    detail->attributes = NULL;
    if (GNUNET_OK !=
        GNUNET_JSON_parse (obj,
                           spec,
                           NULL,
                           NULL))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    detail->by_aml_officer = by_aml_officer;
  }
  return GNUNET_OK;
}


/**
 * Parse the provided data from the "200 OK" response.
 *
 * @param[in,out] aagh handle (callback may be zero'ed out)
 * @param json json reply with the data
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
 */
static enum GNUNET_GenericReturnValue
parse_get_aml_attributes_ok (
  struct TALER_EXCHANGE_GetAmlAttributesHandle *aagh,
  const json_t *json)
{
  struct TALER_EXCHANGE_GetAmlAttributesResponse lr = {
    .hr.reply = json,
    .hr.http_status = MHD_HTTP_OK
  };
  const json_t *jdetails;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_array_const ("details",
                                  &jdetails),
    GNUNET_JSON_spec_end ()
  };

  if (GNUNET_OK !=
      GNUNET_JSON_parse (json,
                         spec,
                         NULL,
                         NULL))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  lr.details.ok.details_length = json_array_size (jdetails);
  {
    struct TALER_EXCHANGE_GetAmlAttributesCollectionEvent details[
      GNUNET_NZL (lr.details.ok.details_length)];

    memset (details,
            0,
            sizeof (details));
    lr.details.ok.details = details;
    if (GNUNET_OK !=
        parse_attributes (jdetails,
                          details))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    aagh->cb (aagh->cb_cls,
              &lr);
    aagh->cb = NULL;
  }
  return GNUNET_OK;
}


/**
 * Function called when we're done processing the
 * HTTP GET /aml/$OFFICER_PUB/attributes/$H_NORMALIZED_PAYTO request (new API).
 *
 * @param cls the `struct TALER_EXCHANGE_GetAmlAttributesHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response parsed JSON result, NULL on error
 */
static void
handle_get_aml_attributes_finished (void *cls,
                                    long response_code,
                                    const void *response)
{
  struct TALER_EXCHANGE_GetAmlAttributesHandle *aagh = cls;
  const json_t *j = response;
  struct TALER_EXCHANGE_GetAmlAttributesResponse lr = {
    .hr.reply = j,
    .hr.http_status = (unsigned int) response_code
  };

  aagh->job = NULL;
  switch (response_code)
  {
  case 0:
    lr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_OK:
    if (GNUNET_OK !=
        parse_get_aml_attributes_ok (aagh,
                                     j))
    {
      GNUNET_break_op (0);
      lr.hr.http_status = 0;
      lr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
      break;
    }
    GNUNET_assert (NULL == aagh->cb);
    TALER_EXCHANGE_get_aml_attributes_cancel (aagh);
    return;
  case MHD_HTTP_NO_CONTENT:
    break;
  case MHD_HTTP_NOT_IMPLEMENTED:
    lr.hr.ec = TALER_JSON_get_error_code (j);
    lr.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  case MHD_HTTP_BAD_REQUEST:
    lr.hr.ec = TALER_JSON_get_error_code (j);
    lr.hr.hint = TALER_JSON_get_error_hint (j);
    /* This should never happen, either us or the exchange is buggy
       (or API version conflict); just pass JSON reply to the application */
    break;
  case MHD_HTTP_FORBIDDEN:
    lr.hr.ec = TALER_JSON_get_error_code (j);
    lr.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  case MHD_HTTP_NOT_FOUND:
    lr.hr.ec = TALER_JSON_get_error_code (j);
    lr.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  case MHD_HTTP_NOT_ACCEPTABLE:
    lr.hr.ec = TALER_JSON_get_error_code (j);
    lr.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    lr.hr.ec = TALER_JSON_get_error_code (j);
    lr.hr.hint = TALER_JSON_get_error_hint (j);
    /* Server had an internal issue; we should retry, but this API
       leaves this to the application */
    break;
  default:
    /* unexpected response code */
    GNUNET_break_op (0);
    lr.hr.ec = TALER_JSON_get_error_code (j);
    lr.hr.hint = TALER_JSON_get_error_hint (j);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d for get AML attributes\n",
                (unsigned int) response_code,
                (int) lr.hr.ec);
    break;
  }
  if (NULL != aagh->cb)
    aagh->cb (aagh->cb_cls,
              &lr);
  TALER_EXCHANGE_get_aml_attributes_cancel (aagh);
}


struct TALER_EXCHANGE_GetAmlAttributesHandle *
TALER_EXCHANGE_get_aml_attributes_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const struct TALER_AmlOfficerPrivateKeyP *officer_priv,
  const struct TALER_NormalizedPaytoHashP *h_payto)
{
  struct TALER_EXCHANGE_GetAmlAttributesHandle *aagh;

  aagh = GNUNET_new (struct TALER_EXCHANGE_GetAmlAttributesHandle);
  aagh->ctx = ctx;
  aagh->base_url = GNUNET_strdup (url);
  aagh->h_payto = *h_payto;
  aagh->officer_priv = *officer_priv;
  GNUNET_CRYPTO_eddsa_key_get_public (&officer_priv->eddsa_priv,
                                      &aagh->officer_pub.eddsa_pub);
  aagh->options.limit = -20;
  aagh->options.offset = INT64_MAX;
  return aagh;
}


enum GNUNET_GenericReturnValue
TALER_EXCHANGE_get_aml_attributes_set_options_ (
  struct TALER_EXCHANGE_GetAmlAttributesHandle *aagh,
  unsigned int num_options,
  const struct TALER_EXCHANGE_GetAmlAttributesOptionValue *options)
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    const struct TALER_EXCHANGE_GetAmlAttributesOptionValue *opt = &options[i];

    switch (opt->option)
    {
    case TALER_EXCHANGE_GET_AML_ATTRIBUTES_OPTION_END:
      return GNUNET_OK;
    case TALER_EXCHANGE_GET_AML_ATTRIBUTES_OPTION_LIMIT:
      aagh->options.limit = opt->details.limit;
      break;
    case TALER_EXCHANGE_GET_AML_ATTRIBUTES_OPTION_OFFSET:
      if (opt->details.offset > INT64_MAX)
      {
        GNUNET_break (0);
        return GNUNET_NO;
      }
      aagh->options.offset = opt->details.offset;
      break;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_EXCHANGE_get_aml_attributes_start (
  struct TALER_EXCHANGE_GetAmlAttributesHandle *aagh,
  TALER_EXCHANGE_GetAmlAttributesCallback cb,
  TALER_EXCHANGE_GET_AML_ATTRIBUTES_RESULT_CLOSURE *cb_cls)
{
  struct TALER_AmlOfficerSignatureP officer_sig;
  char arg_str[sizeof (aagh->officer_pub) * 2
               + sizeof (aagh->h_payto) * 2
               + 32];
  CURL *eh;

  if (NULL != aagh->job)
  {
    GNUNET_break (0);
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  aagh->cb = cb;
  aagh->cb_cls = cb_cls;
  TALER_officer_aml_query_sign (&aagh->officer_priv,
                                &officer_sig);
  {
    char payto_s[sizeof (aagh->h_payto) * 2];
    char pub_str[sizeof (aagh->officer_pub) * 2];
    char *end;

    end = GNUNET_STRINGS_data_to_string (
      &aagh->h_payto,
      sizeof (aagh->h_payto),
      payto_s,
      sizeof (payto_s));
    *end = '\0';
    end = GNUNET_STRINGS_data_to_string (
      &aagh->officer_pub,
      sizeof (aagh->officer_pub),
      pub_str,
      sizeof (pub_str));
    *end = '\0';
    GNUNET_snprintf (arg_str,
                     sizeof (arg_str),
                     "aml/%s/attributes/%s",
                     pub_str,
                     payto_s);
  }
  {
    char limit_s[24];
    char offset_s[24];

    GNUNET_snprintf (limit_s,
                     sizeof (limit_s),
                     "%lld",
                     (long long) aagh->options.limit);
    GNUNET_snprintf (offset_s,
                     sizeof (offset_s),
                     "%llu",
                     (unsigned long long) aagh->options.offset);
    aagh->url = TALER_url_join (aagh->base_url,
                                arg_str,
                                "limit",
                                limit_s,
                                "offset",
                                offset_s,
                                NULL);
  }
  if (NULL == aagh->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  eh = TALER_EXCHANGE_curl_easy_get_ (aagh->url);
  if (NULL == eh)
  {
    GNUNET_free (aagh->url);
    aagh->url = NULL;
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  }
  {
    struct curl_slist *job_headers = NULL;
    char *hdr;
    char sig_str[sizeof (officer_sig) * 2];
    char *end;

    end = GNUNET_STRINGS_data_to_string (
      &officer_sig,
      sizeof (officer_sig),
      sig_str,
      sizeof (sig_str));
    *end = '\0';
    GNUNET_asprintf (&hdr,
                     "%s: %s",
                     TALER_AML_OFFICER_SIGNATURE_HEADER,
                     sig_str);
    job_headers = curl_slist_append (NULL,
                                     hdr);
    GNUNET_free (hdr);
    aagh->job = GNUNET_CURL_job_add2 (aagh->ctx,
                                      eh,
                                      job_headers,
                                      &handle_get_aml_attributes_finished,
                                      aagh);
    curl_slist_free_all (job_headers);
  }
  if (NULL == aagh->job)
  {
    GNUNET_free (aagh->url);
    aagh->url = NULL;
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  return TALER_EC_NONE;
}


void
TALER_EXCHANGE_get_aml_attributes_cancel (
  struct TALER_EXCHANGE_GetAmlAttributesHandle *aagh)
{
  if (NULL != aagh->job)
  {
    GNUNET_CURL_job_cancel (aagh->job);
    aagh->job = NULL;
  }
  GNUNET_free (aagh->url);
  GNUNET_free (aagh->base_url);
  GNUNET_free (aagh);
}


/* end of exchange_api_lookup_kyc_attributes.c */
