/*
 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 {
  AmountString,
  Logger,
  TalerWireGatewayHttpClient,
  j2s,
} from "@gnu-taler/taler-util";
import { WalletApiOperation } from "@gnu-taler/taler-wallet-core";
import { createSimpleTestkudosEnvironmentV3 } from "../harness/environments.js";
import { GlobalTestState } from "../harness/harness.js";

const logger = new Logger("test-withdrawal-manual.ts");

/**
 * Check what happens when the withdrawal amount unexpectedly changes.
 */
export async function runWithdrawalAmountTest(t: GlobalTestState) {
  // Set up test environment

  const { walletClient, bankClient, exchange, exchangeBankAccount, bank } =
    await createSimpleTestkudosEnvironmentV3(t);

  const wireGatewayApiClient = new TalerWireGatewayHttpClient(
    exchangeBankAccount.wireGatewayApiBaseUrl,
  );

  // Create a withdrawal operation

  const user = await bankClient.createRandomBankUser();

  await walletClient.call(WalletApiOperation.AddExchange, {
    exchangeBaseUrl: exchange.baseUrl,
  });

  logger.info("starting AcceptManualWithdrawal request");

  const wres = await walletClient.call(
    WalletApiOperation.AcceptManualWithdrawal,
    {
      exchangeBaseUrl: exchange.baseUrl,
      amount: "TESTKUDOS:10" as AmountString,
    },
  );

  logger.info("AcceptManualWithdrawal finished");
  logger.info(`result: ${j2s(wres)}`);

  const reservePub: string = wres.reservePub;

  await wireGatewayApiClient.addIncoming({
    auth: bank.getAdminAuth(),
    body: {
      amount: "TESTKUDOS:5",
      debit_account: user.accountPaytoUri,
      reserve_pub: reservePub,
    },
  });

  await exchange.runWirewatchOnce();

  await walletClient.call(WalletApiOperation.TestingWaitTransactionsFinal, {});

  // Check balance

  const balResp = await walletClient.call(WalletApiOperation.GetBalances, {});

  // We managed to withdraw the actually transferred amount!
  t.assertAmountEquals(balResp.balances[0].available, "TESTKUDOS:4.85");

  await t.shutdown();
}

runWithdrawalAmountTest.suites = ["wallet"];
