/*
 This file is part of GNU Taler
 (C) 2020 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 { MerchantApiClient, TalerCorebankApiClient } from "@gnu-taler/taler-util";
import { WalletApiOperation } from "@gnu-taler/taler-wallet-core";
import { coin_ct10, coin_u1 } from "../harness/denomStructures.js";
import {
  BankService,
  ExchangeService,
  GlobalTestState,
  MerchantService,
  generateRandomPayto,
  setupDb,
} from "../harness/harness.js";
import {
  createWalletDaemonWithClient,
  withdrawViaBankV3,
} from "../harness/helpers.js";

async function setupTest(t: GlobalTestState): Promise<{
  merchant: MerchantService;
  exchange: ExchangeService;
  bankClient: TalerCorebankApiClient;
}> {
  const db = await setupDb(t);

  const bank = await BankService.create(t, {
    allowRegistrations: true,
    currency: "TESTKUDOS",
    database: db.connStr,
    httpPort: 8082,
  });

  const exchange = ExchangeService.create(t, {
    name: "testexchange-1",
    currency: "TESTKUDOS",
    httpPort: 8081,
    database: db.connStr,
  });

  exchange.addOfferedCoins([coin_ct10, coin_u1]);

  let receiverName = "Exchange";
  let exchangeBankUsername = "exchange";
  let exchangeBankPassword = "mypw";
  let exchangePaytoUri = generateRandomPayto(exchangeBankUsername);

  await exchange.addBankAccount("1", {
    accountName: exchangeBankUsername,
    accountPassword: exchangeBankPassword,
    wireGatewayApiBaseUrl: new URL("accounts/exchange/taler-wire-gateway/", bank.baseUrl).href,
    accountPaytoUri: exchangePaytoUri,
  });

  bank.setSuggestedExchange(exchange, exchangePaytoUri);

  await bank.start();

  await bank.pingUntilAvailable();

  const bankClient = new TalerCorebankApiClient(bank.corebankApiBaseUrl, {
    auth: {
      username: "admin",
      password: "adminpw",
    },
  });

  await bankClient.registerAccountExtended({
    name: receiverName,
    password: exchangeBankPassword,
    username: exchangeBankUsername,
    is_taler_exchange: true,
    payto_uri: exchangePaytoUri,
  });

  await exchange.start();
  await exchange.pingUntilAvailable();

  const merchant = await MerchantService.create(t, {
    name: "testmerchant-1",
    currency: "TESTKUDOS",
    httpPort: 8083,
    database: db.connStr,
  });

  merchant.addExchange(exchange);

  await merchant.start();
  await merchant.pingUntilAvailable();

  await merchant.addInstanceWithWireAccount({
    id: "default",
    name: "Default Instance",
    paytoUris: [generateRandomPayto("merchant-default")],
  });

  await merchant.addInstanceWithWireAccount({
    id: "minst1",
    name: "minst1",
    paytoUris: [generateRandomPayto("minst1")],
  });

  console.log("setup done!");

  return {
    merchant,
    bankClient,
    exchange,
  };
}

/**
 * Run test.
 *
 * This test uses a very sub-optimal denomination structure.
 */
export async function runPaymentMultipleTest(t: GlobalTestState) {
  // Set up test environment

  const { merchant, bankClient, exchange } = await setupTest(t);

  const { walletClient } = await createWalletDaemonWithClient(t, {
    name: "default",
  });

  const merchantClient = new MerchantApiClient(merchant.makeInstanceBaseUrl());

  // Withdraw digital cash into the wallet.

  const wres = await withdrawViaBankV3(t, {
    walletClient,
    bankClient,
    exchange,
    amount: "TESTKUDOS:100",
  });

  await wres.withdrawalFinishedCond;

  // Set up order.

  const orderResp = await merchantClient.createOrder({
    order: {
      summary: "Buy me!",
      amount: "TESTKUDOS:80",
      fulfillment_url: "taler://fulfillment-success/thx",
    },
  });

  let orderStatus = await merchantClient.queryPrivateOrderStatus({
    orderId: orderResp.order_id,
  });

  t.assertTrue(orderStatus.order_status === "unpaid");

  // Make wallet pay for the order

  const r1 = await walletClient.call(WalletApiOperation.PreparePayForUri, {
    talerPayUri: orderStatus.taler_pay_uri,
  });

  await walletClient.call(WalletApiOperation.ConfirmPay, {
    transactionId: r1.transactionId,
  });

  // Check if payment was successful.

  orderStatus = await merchantClient.queryPrivateOrderStatus({
    orderId: orderResp.order_id,
  });

  t.assertTrue(orderStatus.order_status === "paid");

  await t.shutdown();
}

runPaymentMultipleTest.suites = ["wallet"];
runPaymentMultipleTest.timeoutMs = 120000;
