/*
  This file is part of TALER
  (C) 2015, 2021 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 util/test_contract.c
 * @brief Tests for contract parsing/serializing
 * @author Iván Ávalos (ivan@avalos.me)
 */

#include "platform.h"
#include <gnunet/gnunet_util_lib.h>
#include <gnunet/gnunet_common.h>
#include <gnunet/gnunet_json_lib.h>
#include "taler_merchant_util.h"
#include <jansson.h>

const char *contract_common = "{\n"
                              "  \"summary\": \"Test order\",\n"
                              "  \"summary_i18n\": {\n"
                              "    \"en\": \"Test order\",\n"
                              "    \"es\": \"Orden de prueba\"\n"
                              "  },\n"
                              "  \"order_id\": \"test\",\n"
                              "  \"public_reorder_url\": \"https://test.org/reorder\",\n"
                              "  \"fulfillment_url\": \"https://test.org/fulfillment\",\n"
                              "  \"fulfillment_message\": \"Thank you for your purchase!\",\n"
                              "  \"fulfillment_message_i18n\": {\n"
                              "    \"en\": \"Thank you for your purchase!\",\n"
                              "    \"es\": \"¡Gracias por su compra!\"\n"
                              "  },\n"
                              "  \"products\": [],\n"
                              "  \"timestamp\": {\"t_s\": 1736174497},\n"
                              "  \"refund_deadline\": {\"t_s\": 1736174497},\n"
                              "  \"pay_deadline\": {\"t_s\": 1736174497},\n"
                              "  \"wire_transfer_deadline\": {\"t_s\": 1736174497},\n"
                              "  \"merchant_pub\": \"F80MFRG8HVH6R9CQ47KRFQSJP3T6DBJ4K1D9B703RJY3Z39TBMJ0\",\n"
                              "  \"merchant_base_url\": \"https://test.org/merchant\",\n"
                              "  \"merchant\": {\n"
                              "    \"name\": \"Test merchant\",\n"
                              "    \"email\": \"test@test.org\",\n"
                              "    \"website\": \"https://test.org/merchant\",\n"
                              "    \"logo\": \"data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAA7EAAAOxAGVKw4bAAADRUlEQVRYhe2WXUgUURiG39l1Vt021C2piJAQyhXEXVNKysoSd8nywgLNn1CIMCLposCLxOii8KasC2+CFB1WRVASMpMUKiyIaLXyBwmhoh9Kzc1W929murAZ9+znZl2EXey5OvOc93zfO+ec+eZwZmuLjFVsmtVMHjYQNvBfGIhYSSAD6LcXYJ1RrzLO1AhzAg9oNHD0FGPBLSJ2bwuSjRE4U2rCydIdmJpxIae4C9wK8blQdUCWgaH7pepzZXUf3rx34eqFXcgwbwIANLUP40bjKzzuLIRBzwMATFY7ojgJL3pL1eRmqwAuhJNlDSiTTQebEcUv7pKjd9GMxSaouj9hHp+M0f4yeH0Sdh6xEwPkDOTu2QzuV4CVkltsAkYnptTxQI3CInkOFpsAHa9Byjbj7w2Ikoy6i9lMIh+nDfmWAFBS1UuYonX6OIY13zwEOWi9GQMv+8pwS3Awgtf3jjPJg5ME9wPZZH8Jw7r7JphzRQwAQIMwovZHZ/wkcF11Jj5/cRHumvfjVFES4Z/mRLVfe+0ZGVcNLHglMjg3eALff3gZlrs/ETnFnUSbdtiO0+XpDHN7RIz1FBKtKC3tg2rAtDUG35xuRqjjNdhd2EUC8BH0m9LraE2rrO5DXEwU4ZJ2qfyos6adXqw1RBKx0bBirQrZJj/MEyaKQKxeu4yBWTcitOybuT0i7t7OJ0G8flq7PD7KepryMb/AniOtFph1eqgB3TLLGpPVAsManmF3escx0HqUaB92HENH9wjDDHoeG7PpFxK4hWTjqspT1H6ykS7/pfrn2BCvJzzeGI0rDQ7CE2OXYtScTSfjjIFUq4CKolRGkJrXxhQZpQWyUOPbc9nSW5CXBLOVXRHGgIYDzl8eYAJqRD9JohSe+toswgK1eo3EsPJzPeSnRLag/8lHdYJy2ILru8L2ZSao/4Tg5ApzeaTFWD4Jw+MzwemWvw9YbAJkGRh5UAZg8ddssQmIitapCeZcXlhsAmqq0lX26Ok7bDlgR17Gesas2SaEvBeEvA8oTZaBgbYCGOP0aG534HrjCIam/XAPliFSp0VaXitkUcTQWx/ksQp13tdpF3JLaBH7awP/uq36nTBsIGxg1Q38BGj1Qe2GKmj3AAAAAElFTkSuQmCC\",\n"
                              "    \"address\": {},\n" // TODO
                              "    \"jurisdiction\": {}\n" // TODO
                              "  },\n"
                              "  \"h_wire\": \"WYEMPXPRA87Y1QBJAJSR5SMB8V3QN2MMHAKDAEN04XC8TQ6TBEJF5KAKT3Y8KKP9W0TW3A2PH1YB22EZJ9TA7HX1P5BFTJQ660GS1TG\",\n"
                              "  \"wire_method\": \"iban\",\n"
                              "  \"exchanges\": [],\n"
                              "  \"delivery_location\": {},\n" // TODO
                              "  \"delivery_date\": {\"t_s\": 1736174497},\n"
                              "  \"nonce\": \"\",\n" // TODO
                              "  \"auto_refund\": {\"d_us\": \"forever\"},\n"
                              "  \"extra\": {\n"
                              "    \"key0\": \"value0\",\n"
                              "    \"key1\": \"value1\",\n"
                              "    \"key2\": 2\n"
                              "  },\n"
                              "  \"minimum_age\": 100\n"
                              "}";

const char *contract_v0 = "{\n"
                          "  \"version\": 0,\n"
                          "  \"amount\": \"KUDOS:10\",\n"
                          "  \"max_fee\": \"KUDOS:0.2\"\n"
                          "}";

const char *contract_v1 = "{\n"
                          "  \"version\": 1,\n"
                          "  \"choices\": [\n"
                          "    {\n"
                          "      \"amount\": \"KUDOS:1\",\n"
                          "      \"max_fee\": \"KUDOS:0.5\",\n"
                          "      \"description\": \"Subscription in, discount out\",\n"
                          "      \"description_i18n\": {\n"
                          "        \"en\": \"This is a test choice\",\n"
                          "        \"es\": \"Esta es una opción de prueba\"\n"
                          "      },\n"
                          "      \"inputs\": [\n"
                          "        {\n"
                          "          \"type\": \"token\",\n"
                          "          \"token_family_slug\": \"test-subscription\",\n"
                          "          \"count\": 1\n"
                          "        }\n"
                          "      ],\n"
                          "      \"outputs\": [\n"
                          "        {\n"
                          "          \"type\": \"token\",\n"
                          "          \"token_family_slug\": \"test-discount\",\n"
                          "          \"count\": 2,\n"
                          "          \"key_index\": 0\n" // TODO
                          "        },\n"
                          "        {\n"
                          "          \"type\": \"tax-receipt\",\n"
                          "          \"donau_urls\": [\"a\", \"b\", \"c\"],\n"
                          "          \"amount\": \"KUDOS:10\"\n"
                          "        }\n"
                          "      ]\n"
                          "    }\n"
                          "  ],\n"
                          "  \"token_families\": {\n"
                          "    \"test-subscription\": {\n"
                          "      \"name\": \"Test subscription\",\n"
                          "      \"description\": \"This is a test subscription\",\n"
                          "      \"description_i18n\": {\n"
                          "        \"en\": \"This is a test subscription\",\n"
                          "        \"es\": \"Esta es una subscripción de prueba\"\n"
                          "      },\n"
                          "      \"keys\": [\n"
                          "        {\n"
                          "          \"cipher\": \"CS\",\n"
                          "          \"cs_pub\": \"AMGKHAWCF3Y32E64G6JV7TPP7KHE2C3QFMNZ8N66Q744FV3TH1D0\",\n"
                          "          \"signature_validity_start\": {\"t_s\": 1736174497},\n"
                          "          \"signature_validity_end\": {\"t_s\": 1736174497}\n"
                          "        }\n"
                          "      ],\n"
                          "      \"details\": {\n"
                          "        \"class\": \"subscription\",\n"
                          "        \"trusted_domains\": [\"a\", \"b\", \"c\"]\n"
                          "      },\n"
                          "      \"critical\": true\n"
                          "    },\n"
                          "    \"test-discount\": {\n"
                          "      \"name\": \"Test discount\",\n"
                          "      \"description\": \"This is a test discount\",\n"
                          "      \"description_i18n\": {\n"
                          "        \"en\": \"This is a test discount\",\n"
                          "        \"es\": \"Este es un descuento de prueba\"\n"
                          "      },\n"
                          "      \"keys\": [\n"
                          "        {\n"
                          "          \"cipher\": \"RSA\",\n"
                          "          \"rsa_pub\": \"040000YGF5DK0PKCN99J0V814C20Q54C82S3RE3GBVC2T4QXEP7N05ABAN5DG8BC3FTN33BSG15VFX2N9X95HE7GBDAHSYHG4G00VHDCV4E0W4HVYTZGN6SGPBMTAE1XMYBH5DFWT4TXPSEQB96AG3G65X6BPQ0WXSARD5NP2YR1CQB6GB0W2BSKZK1AXZN67GHB3HHAPFV8V584QF1DGDXEWN875RN4HYNH3AW4XZ9SP5A7J5MED56P0TXX5D8C1HPWHFD89GE6Q7J0Q3QKM18WAVAZJTF6PR3Q5T2C71ST0VTP42F16ZZRWS4CHSXHM5RW0BGH383VX4100AD61X6QQ99K12Q17EQZK5MSE6AGNK24SCAH06XTXA7WFC78V0ARJKFDX1M483GE9SX20XXFKSTQ6B8104002\",\n"
                          "          \"signature_validity_start\": {\"t_s\": 1736174497},\n"
                          "          \"signature_validity_end\": {\"t_s\": 1736174497}\n"
                          "        }\n"
                          "      ],\n"
                          "      \"details\": {\n"
                          "        \"class\": \"discount\",\n"
                          "        \"expected_domains\": [\"a\", \"b\", \"c\"]\n"
                          "      },\n"
                          "      \"critical\": true\n"
                          "    }\n"
                          "  }\n"
                          "}";


int
main (int argc,
      const char *const argv[])
{
  (void) argc;
  (void) argv;
  GNUNET_log_setup ("test-contract",
                    "WARNING",
                    NULL);

  { // Contract v0
    json_t *common;
    json_t *v0;
    struct TALER_MERCHANT_Contract *v0_parsed;
    json_t *v0_serialized;

    common = json_loads (contract_common, 0, NULL);
    GNUNET_assert (NULL != common);

    v0 = json_loads (contract_v0, 0, NULL);
    GNUNET_assert (NULL != v0);

    GNUNET_assert (0 == json_object_update_new (v0, common));

    v0_parsed = TALER_MERCHANT_contract_parse (v0, false);
    GNUNET_assert (NULL != v0_parsed);

    v0_serialized = TALER_MERCHANT_contract_serialize (v0_parsed, false);
    GNUNET_assert (NULL != v0_serialized);

    GNUNET_assert (1 == json_equal (v0, v0_serialized));

    json_decref (v0_serialized);
    TALER_MERCHANT_contract_free (v0_parsed);
    json_decref (v0);
  }

  { // Contract v1
    json_t *common;
    json_t *v1;
    struct TALER_MERCHANT_Contract *v1_parsed;
    json_t *v1_serialized;

    common = json_loads (contract_common, 0, NULL);
    GNUNET_assert (NULL != common);

    v1 = json_loads (contract_v1, 0, NULL);
    GNUNET_assert (NULL != v1);

    GNUNET_assert (0 == json_object_update_new (v1, common));

    v1_parsed = TALER_MERCHANT_contract_parse (v1, false);
    GNUNET_assert (NULL != v1_parsed);

    v1_serialized = TALER_MERCHANT_contract_serialize (v1_parsed, false);
    GNUNET_assert (NULL != v1_serialized);

    GNUNET_assert (1 == json_equal (v1, v1_serialized));

    for (unsigned int i = 0;
         i < v1_parsed->details.v1.token_authorities_len;
         i++)
    {
      struct TALER_MERCHANT_ContractTokenFamily *in =
        &v1_parsed->details.v1.token_authorities[i];
      for (unsigned int j = 0; j < in->keys_len; j++)
      {
        struct TALER_MERCHANT_ContractTokenFamilyKey *inkey = &in->keys[j];
        struct TALER_MERCHANT_ContractTokenFamily out;
        struct TALER_MERCHANT_ContractTokenFamilyKey outkey;
        GNUNET_assert (GNUNET_OK == TALER_MERCHANT_find_token_family_key (
                         in->slug,
                         inkey->valid_after,
                         v1_parsed->details.v1.token_authorities,
                         v1_parsed->details.v1.token_authorities_len,
                         &out,
                         &outkey));
        GNUNET_assert (0 == GNUNET_memcmp (in, &out));
        GNUNET_assert (0 == GNUNET_memcmp (inkey, &outkey));
      }
    }

    json_decref (v1_serialized);
    TALER_MERCHANT_contract_free (v1_parsed);
    json_decref (v1);
  }

  return 0;
}
