/*
  This file is part of TALER
  (C) 2024, 2025 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 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 src/util/order_parse.c
 * @brief shared logic for order parsing
 * @author Iván Ávalos
 * @author Christian Grothoff
 */
#include "platform.h"
#include <gnunet/gnunet_common.h>
#include <gnunet/gnunet_json_lib.h>
#include <jansson.h>
#include <stdbool.h>
#include <stdint.h>
#include <taler/taler_json_lib.h>
#include <taler/taler_util.h>
#include "taler/taler_merchant_util.h"


/**
 * Parse v0-specific fields of @a input JSON into @a order.
 *
 * @param[in] input the JSON order terms
 * @param[out] order where to write the data
 * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error
 */
static enum GNUNET_GenericReturnValue
parse_order_v0 (
  json_t *input,
  struct TALER_MERCHANT_Order *order)
{
  struct GNUNET_JSON_Specification espec[] = {
    TALER_JSON_spec_amount_any ("amount",
                                &order->details.v0.brutto),
    GNUNET_JSON_spec_mark_optional (
      TALER_JSON_spec_amount_any ("tip",
                                  &order->details.v0.tip),
      &order->details.v0.no_tip),
    GNUNET_JSON_spec_mark_optional (
      TALER_JSON_spec_amount_any ("max_fee",
                                  &order->details.v0.max_fee),
      &order->details.v0.no_max_fee),
    GNUNET_JSON_spec_end ()
  };
  enum GNUNET_GenericReturnValue res;
  const char *ename;
  unsigned int eline;

  res = GNUNET_JSON_parse (input,
                           espec,
                           &ename,
                           &eline);
  if (GNUNET_OK != res)
  {
    GNUNET_break (0);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to parse order v0 at field %s\n",
                ename);
    return GNUNET_SYSERR;
  }

  if ( (! order->details.v0.no_max_fee) &&
       (GNUNET_OK !=
        TALER_amount_cmp_currency (&order->details.v0.max_fee,
                                   &order->details.v0.brutto)) )
  {
    GNUNET_break (0);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "'max_fee' does not match currency of order price");
    return GNUNET_SYSERR;
  }
  if ( (! order->details.v0.no_tip) &&
       (GNUNET_OK !=
        TALER_amount_cmp_currency (&order->details.v0.tip,
                                   &order->details.v0.brutto)) )
  {
    GNUNET_break (0);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "'tip' does not match currency of order price");
    return GNUNET_SYSERR;
  }

  return res;
}


/**
 * Parse v1-specific fields of @a input JSON into @a order.
 *
 * @param[in] input the JSON order terms
 * @param[out] order where to write the data
 * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error
 */
static enum GNUNET_GenericReturnValue
parse_order_v1 (
  json_t *input,
  struct TALER_MERCHANT_Order *order)
{
  struct GNUNET_JSON_Specification espec[] = {
    TALER_MERCHANT_spec_order_choices (
      "choices",
      &order->details.v1.choices,
      &order->details.v1.choices_len),
    GNUNET_JSON_spec_end ()
  };

  enum GNUNET_GenericReturnValue res;
  const char *ename;
  unsigned int eline;

  res = GNUNET_JSON_parse (input,
                           espec,
                           &ename,
                           &eline);
  if (GNUNET_OK != res)
  {
    GNUNET_break (0);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to parse order v1 at field %s\n",
                ename);
    return GNUNET_SYSERR;
  }

  return res;
}


struct TALER_MERCHANT_Order *
TALER_MERCHANT_order_parse (json_t *input)
{
  struct TALER_MERCHANT_Order *order
    = GNUNET_new (struct TALER_MERCHANT_Order);
  enum GNUNET_GenericReturnValue res
    = GNUNET_SYSERR;

  GNUNET_assert (NULL != input);
  order->base = TALER_MERCHANT_base_terms_parse (input);
  if (NULL == order->base)
  {
    GNUNET_break (0);
    GNUNET_free (order);
    return NULL;
  }
  order->refund_deadline = GNUNET_TIME_UNIT_FOREVER_TS;
  order->wire_transfer_deadline = GNUNET_TIME_UNIT_FOREVER_TS;
  {
    const json_t *products;
    struct GNUNET_JSON_Specification espec[] = {
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_array_const ("products",
                                      &products),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        TALER_JSON_spec_slug_copy ("order_id",
                                   &order->order_id),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_timestamp ("timestamp",
                                    &order->timestamp),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_timestamp ("refund_deadline",
                                    &order->refund_deadline),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_timestamp ("pay_deadline",
                                    &order->pay_deadline),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_timestamp ("wire_transfer_deadline",
                                    &order->wire_transfer_deadline),
        NULL),
      GNUNET_JSON_spec_end ()
    };
    const char *ename;
    unsigned int eline;

    res = GNUNET_JSON_parse (input,
                             espec,
                             &ename,
                             &eline);
    if (GNUNET_OK != res)
    {
      GNUNET_break_op (0);
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "Failed to parse proto contract at field %s\n",
                  ename);
      goto cleanup;
    }
    if (NULL != products)
    {
      order->products_len = json_array_size (products);
      if (0 != order->products_len)
      {
        size_t i;
        json_t *p;

        order->products = GNUNET_new_array (
          order->products_len,
          struct TALER_MERCHANT_ProductSold);
        json_array_foreach (products, i, p)
        {
          if (GNUNET_OK !=
              TALER_MERCHANT_parse_product_sold (p,
                                                 &order->products[i],
                                                 true))
          {
            GNUNET_break (0);
            GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                        "Failed to parse product at offset %u\n",
                        (unsigned int) i);
            goto cleanup;
          }
        }
      }
    }
  }
  switch (order->base->version)
  {
  case TALER_MERCHANT_CONTRACT_VERSION_0:
    res = parse_order_v0 (input,
                          order);
    break;
  case TALER_MERCHANT_CONTRACT_VERSION_1:
    res = parse_order_v1 (input,
                          order);
    break;
  }

  if (GNUNET_OK != res)
  {
    GNUNET_break (0);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to parse order\n");
    goto cleanup;
  }
  return order;

cleanup:
  TALER_MERCHANT_order_free (order);
  return NULL;
}


void
TALER_MERCHANT_order_free (
  struct TALER_MERCHANT_Order *order)
{
  if (NULL == order)
    return;
  if (NULL != order->products)
  {
    for (size_t i = 0; i<order->products_len; i++)
      TALER_MERCHANT_product_sold_free (&order->products[i]);
    GNUNET_free (order->products);
    order->products_len = 0;
  }
  GNUNET_free (order->order_id);
  if (NULL != order->base)
  {
    switch (order->base->version)
    {
    case TALER_MERCHANT_CONTRACT_VERSION_0:
      break;
    case TALER_MERCHANT_CONTRACT_VERSION_1:
      for (unsigned int i = 0;
           i < order->details.v1.choices_len;
           i++)
        TALER_MERCHANT_order_choice_free (&order->details.v1.choices[i]);
      GNUNET_free (order->details.v1.choices);
      break;
    }
    TALER_MERCHANT_base_terms_free (order->base);
    order->base = NULL;
  }
  GNUNET_free (order);
}
