/*
  This file is part of TALER
  Copyright (C) 2023, 2024, 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-decisions.c
 * @brief Implementation of the /aml/$OFFICER_PUB/decisions 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 "taler/exchange/get-aml-OFFICER_PUB-decisions.h"
#include "exchange_api_handle.h"
#include "taler/taler_signatures.h"
#include "exchange_api_curl_defaults.h"

#define DEBUG 0

/**
 * @brief A GET /aml/$OFFICER_PUB/decisions Handle
 */
struct TALER_EXCHANGE_GetAmlDecisionsHandle
{

  /**
   * The base URL of the exchange.
   */
  char *base_url;

  /**
   * The full URL for this request, set during _start.
   */
  char *url;

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

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

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

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

  /**
   * Public key of the AML officer.
   */
  struct TALER_AmlOfficerPublicKeyP officer_pub;

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

  /**
   * Signature of the AML officer.
   */
  struct TALER_AmlOfficerSignatureP officer_sig;

  /**
   * Options for the request.
   */
  struct
  {
    /**
     * Limit on number of results (-20 by default).
     */
    int64_t limit;

    /**
     * Row offset threshold (INT64_MAX by default).
     */
    uint64_t offset;

    /**
     * Optional account filter; NULL if not set.
     */
    const struct TALER_NormalizedPaytoHashP *h_payto;

    /**
     * Filter for active decisions (YNA_ALL by default).
     */
    enum TALER_EXCHANGE_YesNoAll active;

    /**
     * Filter for investigation status (YNA_ALL by default).
     */
    enum TALER_EXCHANGE_YesNoAll investigation;
  } options;

  /**
   * Flat array of all KYC rules across all decisions (allocated during parse).
   */
  struct TALER_EXCHANGE_GetAmlDecisionsKycRule *all_rules;

  /**
   * Flat array of all measure string pointers across all rules (allocated during parse).
   */
  const char **all_mp;

};


/**
 * Parse the limits/rules object.
 *
 * @param[in,out] adgh handle (used for allocation tracking)
 * @param jlimits JSON object with legitimization rule set data
 * @param[out] limits where to write the parsed rule set
 * @param[in,out] rule_off current offset into adgh->all_rules (advanced)
 * @param[in,out] mp_off current offset into adgh->all_mp (advanced)
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_limits (
  struct TALER_EXCHANGE_GetAmlDecisionsHandle *adgh,
  const json_t *jlimits,
  struct TALER_EXCHANGE_GetAmlDecisionsLegitimizationRuleSet *limits,
  size_t *rule_off,
  size_t *mp_off)
{
  const json_t *jrules;
  const json_t *jcustom_measures;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_timestamp ("expiration_time",
                                &limits->expiration_time),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("successor_measure",
                               &limits->successor_measure),
      NULL),
    GNUNET_JSON_spec_array_const ("rules",
                                  &jrules),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_object_const ("custom_measures",
                                     &jcustom_measures),
      NULL),
    GNUNET_JSON_spec_end ()
  };

  if (GNUNET_OK !=
      GNUNET_JSON_parse (jlimits,
                         spec,
                         NULL,
                         NULL))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  limits->custom_measures = jcustom_measures;

  {
    size_t rule_count = json_array_size (jrules);
    size_t rule_start = *rule_off;

    limits->rules = &adgh->all_rules[rule_start];
    limits->rules_length = rule_count;

    {
      const json_t *jrule;
      size_t ridx;

      json_array_foreach ((json_t *) jrules, ridx, jrule)
      {
        struct TALER_EXCHANGE_GetAmlDecisionsKycRule *r
          = &adgh->all_rules[*rule_off];
        const json_t *jsmeasures;
        struct GNUNET_JSON_Specification rspec[] = {
          TALER_JSON_spec_kycte ("operation_type",
                                 &r->operation_type),
          GNUNET_JSON_spec_mark_optional (
            GNUNET_JSON_spec_string ("rule_name",
                                     &r->rule_name),
            NULL),
          TALER_JSON_spec_amount_any ("threshold",
                                      &r->threshold),
          GNUNET_JSON_spec_relative_time ("timeframe",
                                          &r->timeframe),
          GNUNET_JSON_spec_array_const ("measures",
                                        &jsmeasures),
          GNUNET_JSON_spec_mark_optional (
            GNUNET_JSON_spec_bool ("exposed",
                                   &r->exposed),
            NULL),
          GNUNET_JSON_spec_mark_optional (
            GNUNET_JSON_spec_bool ("is_and_combinator",
                                   &r->is_and_combinator),
            NULL),
          GNUNET_JSON_spec_int64 ("display_priority",
                                  &r->display_priority),
          GNUNET_JSON_spec_end ()
        };

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

        {
          size_t mlen = json_array_size (jsmeasures);
          size_t mp_start = *mp_off;

          r->measures = &adgh->all_mp[mp_start];
          r->measures_length = mlen;

          {
            size_t midx;
            const json_t *jm;

            json_array_foreach (jsmeasures, midx, jm)
            {
              const char *sval = json_string_value (jm);

              if (NULL == sval)
              {
                GNUNET_break_op (0);
                return GNUNET_SYSERR;
              }
              adgh->all_mp[*mp_off] = sval;
              (*mp_off)++;
            }
          }
        }

        (*rule_off)++;
      }
    }
  }

  return GNUNET_OK;
}


/**
 * Parse AML decision records.
 *
 * @param[in,out] adgh handle (for allocations)
 * @param jrecords JSON array of decision records
 * @param records_ar_length length of @a records_ar
 * @param[out] records_ar caller-allocated array to fill
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_aml_decisions (
  struct TALER_EXCHANGE_GetAmlDecisionsHandle *adgh,
  const json_t *jrecords,
  size_t records_ar_length,
  struct TALER_EXCHANGE_GetAmlDecisionsDecision *records_ar)
{
  size_t rule_off = 0;
  size_t mp_off = 0;
  const json_t *obj;
  size_t idx;

  json_array_foreach ((json_t *) jrecords, idx, obj)
  {
    struct TALER_EXCHANGE_GetAmlDecisionsDecision *decision = &records_ar[idx];
    const json_t *jlimits;
    struct GNUNET_JSON_Specification spec[] = {
      GNUNET_JSON_spec_fixed_auto ("h_payto",
                                   &decision->h_payto),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_string ("full_payto",
                                 &decision->full_payto),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_bool ("is_wallet",
                               &decision->is_wallet),
        NULL),
      GNUNET_JSON_spec_uint64 ("rowid",
                               &decision->rowid),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_string ("justification",
                                 &decision->justification),
        NULL),
      GNUNET_JSON_spec_timestamp ("decision_time",
                                  &decision->decision_time),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_object_const ("properties",
                                       &decision->properties),
        NULL),
      GNUNET_JSON_spec_object_const ("limits",
                                     &jlimits),
      GNUNET_JSON_spec_bool ("to_investigate",
                             &decision->to_investigate),
      GNUNET_JSON_spec_bool ("is_active",
                             &decision->is_active),
      GNUNET_JSON_spec_end ()
    };

    GNUNET_assert (idx < records_ar_length);
    if (GNUNET_OK !=
        GNUNET_JSON_parse (obj,
                           spec,
                           NULL,
                           NULL))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }

    if (GNUNET_OK !=
        parse_limits (adgh,
                      jlimits,
                      &decision->limits,
                      &rule_off,
                      &mp_off))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


/**
 * Parse the provided decision data from the "200 OK" response.
 *
 * @param[in,out] adgh 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_decisions_ok (struct TALER_EXCHANGE_GetAmlDecisionsHandle *adgh,
                            const json_t *json)
{
  struct TALER_EXCHANGE_GetAmlDecisionsResponse lr = {
    .hr.reply = json,
    .hr.http_status = MHD_HTTP_OK
  };
  const json_t *jrecords;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_array_const ("records",
                                  &jrecords),
    GNUNET_JSON_spec_end ()
  };

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

  lr.details.ok.records_length = json_array_size (jrecords);

  /* First pass: count total rules and measures across all records */
  {
    size_t total_rules = 0;
    size_t total_measures = 0;
    const json_t *obj;
    size_t idx;

    json_array_foreach ((json_t *) jrecords, idx, obj)
    {
      const json_t *jlimits = json_object_get (obj, "limits");
      const json_t *jrules;

      if (NULL == jlimits)
        continue;
      jrules = json_object_get (jlimits, "rules");
      if (NULL == jrules)
        continue;
      total_rules += json_array_size (jrules);

      {
        const json_t *jrule;
        size_t ridx;

        json_array_foreach ((json_t *) jrules, ridx, jrule)
        {
          const json_t *jmeasures = json_object_get (jrule, "measures");

          if (NULL != jmeasures)
            total_measures += json_array_size (jmeasures);
        }
      }
    }

    adgh->all_rules = GNUNET_new_array (
      GNUNET_NZL (total_rules),
      struct TALER_EXCHANGE_GetAmlDecisionsKycRule);
    adgh->all_mp = GNUNET_new_array (
      GNUNET_NZL (total_measures),
      const char *);
  }

  {
    struct TALER_EXCHANGE_GetAmlDecisionsDecision records[
      GNUNET_NZL (lr.details.ok.records_length)];
    enum GNUNET_GenericReturnValue ret;

    memset (records,
            0,
            sizeof (records));
    lr.details.ok.records = records;
    ret = parse_aml_decisions (adgh,
                               jrecords,
                               lr.details.ok.records_length,
                               records);
    if (GNUNET_OK == ret)
    {
      adgh->cb (adgh->cb_cls,
                &lr);
      adgh->cb = NULL;
    }
    GNUNET_free (adgh->all_rules);
    adgh->all_rules = NULL;
    GNUNET_free (adgh->all_mp);
    adgh->all_mp = NULL;
    return ret;
  }
}


/**
 * Function called when we're done processing the
 * HTTP /aml/$OFFICER_PUB/decisions request.
 *
 * @param cls the `struct TALER_EXCHANGE_GetAmlDecisionsHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response parsed JSON result, NULL on error
 */
static void
handle_get_aml_decisions_finished (void *cls,
                                   long response_code,
                                   const void *response)
{
  struct TALER_EXCHANGE_GetAmlDecisionsHandle *adgh = cls;
  const json_t *j = response;
  struct TALER_EXCHANGE_GetAmlDecisionsResponse lr = {
    .hr.reply = j,
    .hr.http_status = (unsigned int) response_code
  };

  adgh->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_decisions_ok (adgh,
                                    j))
    {
      GNUNET_break_op (0);
      lr.hr.http_status = 0;
      lr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
      break;
    }
    GNUNET_assert (NULL == adgh->cb);
    TALER_EXCHANGE_get_aml_decisions_cancel (adgh);
    return;
  case MHD_HTTP_NO_CONTENT:
    break;
  case MHD_HTTP_BAD_REQUEST:
#if DEBUG
    json_dumpf (j,
                stderr,
                JSON_INDENT (2));
#endif
    lr.hr.ec = TALER_JSON_get_error_code (j);
    lr.hr.hint = TALER_JSON_get_error_hint (j);
    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_INTERNAL_SERVER_ERROR:
    lr.hr.ec = TALER_JSON_get_error_code (j);
    lr.hr.hint = TALER_JSON_get_error_hint (j);
    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 decisions\n",
                (unsigned int) response_code,
                (int) lr.hr.ec);
    break;
  }
  if (NULL != adgh->cb)
    adgh->cb (adgh->cb_cls,
              &lr);
  TALER_EXCHANGE_get_aml_decisions_cancel (adgh);
}


struct TALER_EXCHANGE_GetAmlDecisionsHandle *
TALER_EXCHANGE_get_aml_decisions_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const struct TALER_AmlOfficerPrivateKeyP *officer_priv)
{
  struct TALER_EXCHANGE_GetAmlDecisionsHandle *adgh;

  adgh = GNUNET_new (struct TALER_EXCHANGE_GetAmlDecisionsHandle);
  adgh->ctx = ctx;
  adgh->base_url = GNUNET_strdup (url);
  adgh->officer_priv = *officer_priv;
  GNUNET_CRYPTO_eddsa_key_get_public (&officer_priv->eddsa_priv,
                                      &adgh->officer_pub.eddsa_pub);
  adgh->options.limit = -20;
  adgh->options.offset = INT64_MAX;
  adgh->options.active = TALER_EXCHANGE_YNA_ALL;
  adgh->options.investigation = TALER_EXCHANGE_YNA_ALL;
  return adgh;
}


enum GNUNET_GenericReturnValue
TALER_EXCHANGE_get_aml_decisions_set_options_ (
  struct TALER_EXCHANGE_GetAmlDecisionsHandle *adgh,
  unsigned int num_options,
  const struct TALER_EXCHANGE_GetAmlDecisionsOptionValue options[])
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    const struct TALER_EXCHANGE_GetAmlDecisionsOptionValue *opt = &options[i];

    switch (opt->option)
    {
    case TALER_EXCHANGE_GET_AML_DECISIONS_OPTION_END:
      return GNUNET_OK;
    case TALER_EXCHANGE_GET_AML_DECISIONS_OPTION_LIMIT:
      adgh->options.limit = opt->details.limit;
      break;
    case TALER_EXCHANGE_GET_AML_DECISIONS_OPTION_OFFSET:
      if (opt->details.offset > INT64_MAX)
      {
        GNUNET_break (0);
        return GNUNET_NO;
      }
      adgh->options.offset = opt->details.offset;
      break;
    case TALER_EXCHANGE_GET_AML_DECISIONS_OPTION_H_PAYTO:
      adgh->options.h_payto = opt->details.h_payto;
      break;
    case TALER_EXCHANGE_GET_AML_DECISIONS_OPTION_ACTIVE:
      adgh->options.active = opt->details.active;
      break;
    case TALER_EXCHANGE_GET_AML_DECISIONS_OPTION_INVESTIGATION:
      adgh->options.investigation = opt->details.investigation;
      break;
    default:
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_EXCHANGE_get_aml_decisions_start (
  struct TALER_EXCHANGE_GetAmlDecisionsHandle *adgh,
  TALER_EXCHANGE_GetAmlDecisionsCallback cb,
  TALER_EXCHANGE_GET_AML_DECISIONS_RESULT_CLOSURE *cb_cls)
{
  CURL *eh;
  char arg_str[sizeof (struct TALER_AmlOfficerPublicKeyP) * 2 + 32];
  struct curl_slist *job_headers = NULL;

  adgh->cb = cb;
  adgh->cb_cls = cb_cls;

  /* Build AML officer signature */
  TALER_officer_aml_query_sign (&adgh->officer_priv,
                                &adgh->officer_sig);

  /* Build the path component: aml/{officer_pub}/decisions */
  {
    char pub_str[sizeof (adgh->officer_pub) * 2];
    char *end;

    end = GNUNET_STRINGS_data_to_string (
      &adgh->officer_pub,
      sizeof (adgh->officer_pub),
      pub_str,
      sizeof (pub_str));
    *end = '\0';
    GNUNET_snprintf (arg_str,
                     sizeof (arg_str),
                     "aml/%s/decisions",
                     pub_str);
  }

  /* Build URL with optional query parameters */
  {
    char limit_s[24];
    char offset_s[24];
    char payto_s[sizeof (*adgh->options.h_payto) * 2 + 1];
    int64_t limit = adgh->options.limit;
    uint64_t offset = adgh->options.offset;
    bool omit_limit = (-20 == limit);
    bool omit_offset = ( ( (limit < 0) && ((uint64_t) INT64_MAX == offset) ) ||
                         ( (limit > 0) && (0 == offset) ) );

    GNUNET_snprintf (limit_s,
                     sizeof (limit_s),
                     "%lld",
                     (long long) limit);
    GNUNET_snprintf (offset_s,
                     sizeof (offset_s),
                     "%llu",
                     (unsigned long long) offset);

    if (NULL != adgh->options.h_payto)
    {
      char *end;

      end = GNUNET_STRINGS_data_to_string (
        adgh->options.h_payto,
        sizeof (*adgh->options.h_payto),
        payto_s,
        sizeof (payto_s) - 1);
      *end = '\0';
    }

    adgh->url = TALER_url_join (
      adgh->base_url,
      arg_str,
      "limit",
      omit_limit ? NULL : limit_s,
      "offset",
      omit_offset ? NULL : offset_s,
      "h_payto",
      (NULL != adgh->options.h_payto) ? payto_s : NULL,
      "active",
      (TALER_EXCHANGE_YNA_ALL != adgh->options.active)
      ? TALER_yna_to_string (adgh->options.active)
      : NULL,
      "investigation",
      (TALER_EXCHANGE_YNA_ALL != adgh->options.investigation)
      ? TALER_yna_to_string (adgh->options.investigation)
      : NULL,
      NULL);
  }

  if (NULL == adgh->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;

  eh = TALER_EXCHANGE_curl_easy_get_ (adgh->url);
  if (NULL == eh)
  {
    GNUNET_break (0);
    GNUNET_free (adgh->url);
    adgh->url = NULL;
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }

  /* Build job headers with AML officer signature */
  {
    char *hdr;
    char sig_str[sizeof (adgh->officer_sig) * 2];
    char *end;

    end = GNUNET_STRINGS_data_to_string (
      &adgh->officer_sig,
      sizeof (adgh->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);
  }

  adgh->job = GNUNET_CURL_job_add2 (adgh->ctx,
                                    eh,
                                    job_headers,
                                    &handle_get_aml_decisions_finished,
                                    adgh);
  curl_slist_free_all (job_headers);

  if (NULL == adgh->job)
  {
    GNUNET_free (adgh->url);
    adgh->url = NULL;
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  }
  return TALER_EC_NONE;
}


void
TALER_EXCHANGE_get_aml_decisions_cancel (
  struct TALER_EXCHANGE_GetAmlDecisionsHandle *adgh)
{
  if (NULL != adgh->job)
  {
    GNUNET_CURL_job_cancel (adgh->job);
    adgh->job = NULL;
  }
  GNUNET_free (adgh->all_rules);
  GNUNET_free (adgh->all_mp);
  GNUNET_free (adgh->url);
  GNUNET_free (adgh->base_url);
  GNUNET_free (adgh);
}


/* end of exchange_api_get-aml-OFFICER_PUB-decisions.c */
