/*
 This file is part of GNU Taler
 (C) 2023 Taler Systems S.A.

 GNU 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.

 GNU 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
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

/**
 * Imports.
 */
import { TalerMerchantInstanceHttpClient } from "@gnu-taler/taler-util";
import { GlobalTestState } from "../harness/harness.js";
import {
  HarnessHttpServer,
  SimpleServerRequest,
} from "../harness/http-server.js";

const contractTerms = {
  amount: "CHF:0.01",
  exchanges: [
    {
      master_pub: "3QMK2XAETQVAGFFS07PKBC6T7509P78WY71KKTQCQ5NRD7RW9SZG",
      max_contribution: "CHF:0.01",
      priority: 1024,
      url: "https://exchange.chf.taler.net/",
    },
  ],
  h_wire:
    "HPRC43CQETW1XGMCHFWE5MNT9J06WBTBZAWTS0BEBX05NKJH7GMSWX0XWF8DWFS4C1FFEEF6YH7RBFMM05EXSPQDW31Q1C9BD5SRKE0",
  max_fee: "CHF:0",
  merchant: {
    address: {},
    jurisdiction: {},
    name: "BFH TI Snack Machine",
    website: "https://bfh.ch/",
    fav_food: "tofu",
  },
  merchant_base_url: "https://backend.chf.taler.net/instances/snack/",
  merchant_pub: "YPTPDHNZJ4QQQ8AS0DP4GHRSDMQ4G9VYFPS1TGM7HNN4XK894DGG",
  minimum_age: 0,
  nonce: "8BANE1BD5TEAAAA44DY0DRRPG3DJFJA2H9PNT11P9Q4AD0TD3SY0",
  order_id: "2025.139-01R8J0HBQ5282",
  pay_deadline: {
    t_s: 1747655143,
  },
  products: [],
  refund_deadline: {
    t_s: 1747820743,
  },
  summary: "Test FD1",
  timestamp: {
    t_s: 1747647943,
  },
  version: 0,
  wire_method: "iban",
  wire_transfer_deadline: {
    t_s: 1747820743,
  },
  foo: 42,
};

/**
 * Test to ensure that the wallet does not throw away unknown fields
 * when parsing contract terms.
 */
export async function runUtilMerchantClientTest(t: GlobalTestState) {
  const server = new HarnessHttpServer();

  server.addSimpleJsonHandler(
    "/orders/myId/claim",
    async (req: SimpleServerRequest) => {
      return {
        status: 200,
        body: { contract_terms: contractTerms, sig: "foo" },
      };
    },
  );

  await server.start(8081);

  const merchantClient = new TalerMerchantInstanceHttpClient(
    "http://localhost:8081",
  );

  const orderResp = await merchantClient.claimOrder({
    body: {
      nonce: "foobar",
    },
    orderId: "myId",
  });

  t.assertDeepEqual(orderResp.case, "ok");
  t.assertDeepEqual(orderResp.body.contract_terms.foo, 42);
  t.assertDeepEqual(orderResp.body.contract_terms.merchant.fav_food, "tofu");

  console.log("yay");

  server.stop();
}

runUtilMerchantClientTest.suites = ["wallet"];
