/*
  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-measures.c
 * @brief Implementation of the GET /aml/$OFFICER_PUB/measures 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-measures.h"
#include "exchange_api_handle.h"
#include "taler/taler_signatures.h"
#include "exchange_api_curl_defaults.h"


/**
 * Scrap buffer of temporary arrays.
 */
struct Scrap
{
  /**
   * Kept in DLL.
   */
  struct Scrap *next;

  /**
   * Kept in DLL.
   */
  struct Scrap *prev;

  /**
   * Pointer to our allocation.
   */
  const char **ptr;
};


/**
 * @brief A GET /aml/$OFFICER_PUB/measures Handle
 */
struct TALER_EXCHANGE_GetAmlMeasuresHandle
{

  /**
   * 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_GetAmlMeasuresCallback cb;

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

  /**
   * Head of scrap list.
   */
  struct Scrap *scrap_head;

  /**
   * Tail of scrap list.
   */
  struct Scrap *scrap_tail;
};


/**
 * Create array of length @a len in scrap book.
 *
 * @param[in,out] amh context for allocations
 * @param len length of array
 * @return scrap array
 */
static const char **
make_scrap (
  struct TALER_EXCHANGE_GetAmlMeasuresHandle *amh,
  unsigned int len)
{
  struct Scrap *s = GNUNET_new (struct Scrap);

  s->ptr = GNUNET_new_array (len,
                             const char *);
  GNUNET_CONTAINER_DLL_insert (amh->scrap_head,
                               amh->scrap_tail,
                               s);
  return s->ptr;
}


/**
 * Free all scrap space.
 *
 * @param[in,out] amh scrap context
 */
static void
free_scrap (struct TALER_EXCHANGE_GetAmlMeasuresHandle *amh)
{
  struct Scrap *s;

  while (NULL != (s = amh->scrap_head))
  {
    GNUNET_CONTAINER_DLL_remove (amh->scrap_head,
                                 amh->scrap_tail,
                                 s);
    GNUNET_free (s->ptr);
    GNUNET_free (s);
  }
}


/**
 * Convert JSON array of strings to string array.
 *
 * @param j JSON array to convert
 * @param[out] a array to initialize
 * @return true on success
 */
static bool
j_to_a (const json_t *j,
        const char **a)
{
  const json_t *e;
  size_t idx;

  json_array_foreach ((json_t *) j, idx, e)
  {
    if (NULL == (a[idx] = json_string_value (e)))
      return false;
  }
  return true;
}


/**
 * Parse AML root measures.
 *
 * @param jroots JSON object with measure data
 * @param[out] roots where to write the result
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_aml_roots (
  const json_t *jroots,
  struct TALER_EXCHANGE_GetAmlMeasuresMeasureInfo *roots)
{
  const json_t *obj;
  const char *name;
  size_t idx = 0;

  json_object_foreach ((json_t *) jroots, name, obj)
  {
    struct TALER_EXCHANGE_GetAmlMeasuresMeasureInfo *root = &roots[idx++];
    struct GNUNET_JSON_Specification spec[] = {
      GNUNET_JSON_spec_string ("check_name",
                               &root->check_name),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_string ("prog_name",
                                 &root->prog_name),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_object_const ("context",
                                       &root->context),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_string ("operation_type",
                                 &root->operation_type),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_bool ("voluntary",
                               &root->voluntary),
        NULL),
      GNUNET_JSON_spec_end ()
    };

    if (GNUNET_OK !=
        GNUNET_JSON_parse (obj,
                           spec,
                           NULL,
                           NULL))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    root->measure_name = name;
  }
  return GNUNET_OK;
}


/**
 * Parse AML programs.
 *
 * @param[in,out] amh context for allocations
 * @param jprogs JSON object with program data
 * @param[out] progs where to write the result
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_aml_programs (
  struct TALER_EXCHANGE_GetAmlMeasuresHandle *amh,
  const json_t *jprogs,
  struct TALER_EXCHANGE_GetAmlMeasuresProgramRequirement *progs)
{
  const json_t *obj;
  const char *name;
  size_t idx = 0;

  json_object_foreach ((json_t *) jprogs, name, obj)
  {
    struct TALER_EXCHANGE_GetAmlMeasuresProgramRequirement *prog = &progs[idx++]
    ;
    const json_t *jcontext;
    const json_t *jinputs;
    struct GNUNET_JSON_Specification spec[] = {
      GNUNET_JSON_spec_string ("description",
                               &prog->description),
      GNUNET_JSON_spec_array_const ("context",
                                    &jcontext),
      GNUNET_JSON_spec_array_const ("inputs",
                                    &jinputs),
      GNUNET_JSON_spec_end ()
    };
    unsigned int len;
    const char **ptr;

    if (GNUNET_OK !=
        GNUNET_JSON_parse (obj,
                           spec,
                           NULL,
                           NULL))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    prog->prog_name = name;
    prog->contexts_length = json_array_size (jcontext);
    prog->inputs_length = json_array_size (jinputs);
    len = (unsigned int) (prog->contexts_length + prog->inputs_length);
    if ( ((size_t) len) != prog->contexts_length + prog->inputs_length)
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    ptr = make_scrap (amh, len);
    prog->contexts = ptr;
    if (! j_to_a (jcontext, prog->contexts))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    prog->inputs = &ptr[prog->contexts_length];
    if (! j_to_a (jinputs, prog->inputs))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


/**
 * Parse KYC checks.
 *
 * @param[in,out] amh context for allocations
 * @param jchecks JSON object with check data
 * @param[out] checks where to write the result
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_aml_checks (
  struct TALER_EXCHANGE_GetAmlMeasuresHandle *amh,
  const json_t *jchecks,
  struct TALER_EXCHANGE_GetAmlMeasuresCheckInfo *checks)
{
  const json_t *obj;
  const char *name;
  size_t idx = 0;

  json_object_foreach ((json_t *) jchecks, name, obj)
  {
    struct TALER_EXCHANGE_GetAmlMeasuresCheckInfo *check = &checks[idx++];
    const json_t *jrequires;
    const json_t *joutputs;
    struct GNUNET_JSON_Specification spec[] = {
      GNUNET_JSON_spec_string ("description",
                               &check->description),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_object_const ("description_i18n",
                                       &check->description_i18n),
        NULL),
      GNUNET_JSON_spec_array_const ("requires",
                                    &jrequires),
      GNUNET_JSON_spec_array_const ("outputs",
                                    &joutputs),
      GNUNET_JSON_spec_string ("fallback",
                               &check->fallback),
      GNUNET_JSON_spec_end ()
    };
    unsigned int len;
    const char **ptr;

    if (GNUNET_OK !=
        GNUNET_JSON_parse (obj,
                           spec,
                           NULL,
                           NULL))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    check->check_name = name;
    check->requires_length = json_array_size (jrequires);
    check->outputs_length = json_array_size (joutputs);
    len = (unsigned int) (check->requires_length + check->outputs_length);
    if ( ((size_t) len) != check->requires_length + check->outputs_length)
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    ptr = make_scrap (amh, len);
    check->requires = ptr;
    if (! j_to_a (jrequires, check->requires))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    check->outputs = &ptr[check->requires_length];
    if (! j_to_a (joutputs, check->outputs))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


/**
 * Parse default KYC rules from the default_rules array.
 *
 * @param[in,out] amh context for allocations
 * @param jrules JSON array with rule data
 * @param[out] rules where to write the result
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
parse_default_rules (
  struct TALER_EXCHANGE_GetAmlMeasuresHandle *amh,
  const json_t *jrules,
  struct TALER_EXCHANGE_GetAmlMeasuresKycRule *rules)
{
  const json_t *obj;
  size_t idx;

  json_array_foreach ((json_t *) jrules, idx, obj)
  {
    struct TALER_EXCHANGE_GetAmlMeasuresKycRule *rule = &rules[idx];
    const json_t *jmeasures;
    struct GNUNET_JSON_Specification spec[] = {
      TALER_JSON_spec_kycte ("operation_type",
                             &rule->operation_type),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_string ("rule_name",
                                 &rule->rule_name),
        NULL),
      TALER_JSON_spec_amount_any ("threshold",
                                  &rule->threshold),
      GNUNET_JSON_spec_relative_time ("timeframe",
                                      &rule->timeframe),
      GNUNET_JSON_spec_array_const ("measures",
                                    &jmeasures),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_bool ("exposed",
                               &rule->exposed),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_bool ("is_and_combinator",
                               &rule->is_and_combinator),
        NULL),
      GNUNET_JSON_spec_int64 ("display_priority",
                              &rule->display_priority),
      GNUNET_JSON_spec_end ()
    };

    if (GNUNET_OK !=
        GNUNET_JSON_parse (obj,
                           spec,
                           NULL,
                           NULL))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    rule->measures_length = json_array_size (jmeasures);
    {
      const char **ptr = make_scrap (amh,
                                     (unsigned int) rule->measures_length);

      rule->measures = ptr;
      if (! j_to_a (jmeasures,
                    ptr))
      {
        GNUNET_break_op (0);
        return GNUNET_SYSERR;
      }
    }
  }
  return GNUNET_OK;
}


/**
 * Parse the provided measures data from the "200 OK" response.
 *
 * @param[in,out] amh 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_measures_ok (struct TALER_EXCHANGE_GetAmlMeasuresHandle *amh,
                           const json_t *json)
{
  struct TALER_EXCHANGE_GetAmlMeasuresResponse lr = {
    .hr.reply = json,
    .hr.http_status = MHD_HTTP_OK
  };
  const json_t *jroots;
  const json_t *jprograms;
  const json_t *jchecks;
  const json_t *jdefault_rules = NULL;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_object_const ("roots",
                                   &jroots),
    GNUNET_JSON_spec_object_const ("programs",
                                   &jprograms),
    GNUNET_JSON_spec_object_const ("checks",
                                   &jchecks),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_array_const ("default_rules",
                                    &jdefault_rules),
      NULL),
    GNUNET_JSON_spec_end ()
  };

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

  lr.details.ok.roots_length = json_object_size (jroots);
  lr.details.ok.programs_length = json_object_size (jprograms);
  lr.details.ok.checks_length = json_object_size (jchecks);
  lr.details.ok.default_rules_length =
    (NULL != jdefault_rules) ? json_array_size (jdefault_rules) : 0;

  {
    struct TALER_EXCHANGE_GetAmlMeasuresMeasureInfo roots[
      GNUNET_NZL (lr.details.ok.roots_length)];
    struct TALER_EXCHANGE_GetAmlMeasuresProgramRequirement progs[
      GNUNET_NZL (lr.details.ok.programs_length)];
    struct TALER_EXCHANGE_GetAmlMeasuresCheckInfo checks[
      GNUNET_NZL (lr.details.ok.checks_length)];
    struct TALER_EXCHANGE_GetAmlMeasuresKycRule drules[
      GNUNET_NZL (lr.details.ok.default_rules_length)];
    enum GNUNET_GenericReturnValue ret;

    memset (roots, 0, sizeof (roots));
    memset (progs, 0, sizeof (progs));
    memset (checks, 0, sizeof (checks));
    memset (drules, 0, sizeof (drules));
    lr.details.ok.roots = roots;
    lr.details.ok.programs = progs;
    lr.details.ok.checks = checks;
    lr.details.ok.default_rules = drules;

    ret = parse_aml_roots (jroots, roots);
    if (GNUNET_OK == ret)
      ret = parse_aml_programs (amh, jprograms, progs);
    if (GNUNET_OK == ret)
      ret = parse_aml_checks (amh, jchecks, checks);
    if ( (GNUNET_OK == ret) && (NULL != jdefault_rules) )
      ret = parse_default_rules (amh, jdefault_rules, drules);
    if (GNUNET_OK == ret)
    {
      amh->cb (amh->cb_cls,
               &lr);
      amh->cb = NULL;
    }
    free_scrap (amh);
    return ret;
  }
}


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

  amh->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_measures_ok (amh,
                                   j))
    {
      GNUNET_break_op (0);
      lr.hr.http_status = 0;
      lr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
      break;
    }
    GNUNET_assert (NULL == amh->cb);
    TALER_EXCHANGE_get_aml_measures_cancel (amh);
    return;
  case MHD_HTTP_NO_CONTENT:
    break;
  case MHD_HTTP_BAD_REQUEST:
    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_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 measures\n",
                (unsigned int) response_code,
                (int) lr.hr.ec);
    break;
  }
  if (NULL != amh->cb)
    amh->cb (amh->cb_cls,
             &lr);
  TALER_EXCHANGE_get_aml_measures_cancel (amh);
}


struct TALER_EXCHANGE_GetAmlMeasuresHandle *
TALER_EXCHANGE_get_aml_measures_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  const struct TALER_AmlOfficerPrivateKeyP *officer_priv)
{
  struct TALER_EXCHANGE_GetAmlMeasuresHandle *amh;

  amh = GNUNET_new (struct TALER_EXCHANGE_GetAmlMeasuresHandle);
  amh->ctx = ctx;
  amh->base_url = GNUNET_strdup (url);
  amh->officer_priv = *officer_priv;
  GNUNET_CRYPTO_eddsa_key_get_public (&officer_priv->eddsa_priv,
                                      &amh->officer_pub.eddsa_pub);
  return amh;
}


enum TALER_ErrorCode
TALER_EXCHANGE_get_aml_measures_start (
  struct TALER_EXCHANGE_GetAmlMeasuresHandle *amh,
  TALER_EXCHANGE_GetAmlMeasuresCallback cb,
  TALER_EXCHANGE_GET_AML_MEASURES_RESULT_CLOSURE *cb_cls)
{
  CURL *eh;
  struct TALER_AmlOfficerSignatureP officer_sig;
  char arg_str[sizeof (struct TALER_AmlOfficerPublicKeyP) * 2 + 32];
  struct curl_slist *job_headers = NULL;

  amh->cb = cb;
  amh->cb_cls = cb_cls;

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

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

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

  amh->url = TALER_url_join (amh->base_url,
                             arg_str,
                             NULL);
  if (NULL == amh->url)
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;

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

  /* Build job headers with AML officer signature */
  {
    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);
  }

  amh->job = GNUNET_CURL_job_add2 (amh->ctx,
                                   eh,
                                   job_headers,
                                   &handle_get_aml_measures_finished,
                                   amh);
  curl_slist_free_all (job_headers);

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


void
TALER_EXCHANGE_get_aml_measures_cancel (
  struct TALER_EXCHANGE_GetAmlMeasuresHandle *amh)
{
  if (NULL != amh->job)
  {
    GNUNET_CURL_job_cancel (amh->job);
    amh->job = NULL;
  }
  free_scrap (amh);
  GNUNET_free (amh->url);
  GNUNET_free (amh->base_url);
  GNUNET_free (amh);
}


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