/*
 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 {
  createEddsaKeyPair,
  encodeCrock,
  j2s,
  succeedOrThrow,
  TalerBankIntegrationHttpClient,
  TalerCoreBankHttpClient,
} from "@gnu-taler/taler-util";
import {
  createSimpleTestkudosEnvironmentV3,
  registerHarnessBankTestUser,
} from "../harness/environments.js";
import { GlobalTestState } from "../harness/harness.js";

/**
 * Test handing over a withdrawal to another wallet.
 */
export async function runBankWopTest(t: GlobalTestState) {
  // Set up test environment

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

  const bankClientNg = new TalerCoreBankHttpClient(bank.corebankApiBaseUrl);

  const bankUser = await registerHarnessBankTestUser(bankClientNg);

  const withdrawalRes = succeedOrThrow(
    await bankClientNg.createWithdrawal(bankUser, {
      amount: "TESTKUDOS:42",
    }),
  );

  const biClient = new TalerBankIntegrationHttpClient(
    `${bank.corebankApiBaseUrl}taler-integration/`,
  );

  const wopid = withdrawalRes.withdrawal_id;

  const wopStatus = succeedOrThrow(
    await biClient.getWithdrawalOperationById(wopid),
  );

  console.log(`${j2s(wopStatus)}`);

  const keyPair = createEddsaKeyPair();

  succeedOrThrow(
    await biClient.completeWithdrawalOperationById(wopid, {
      selected_exchange: exchangeBankAccount.accountPaytoUri,
      reserve_pub: encodeCrock(keyPair.eddsaPub),
    }),
  );

  succeedOrThrow(await bankClientNg.confirmWithdrawalById(bankUser, {}, wopid));

  const wopStatus2 = succeedOrThrow(
    await biClient.getWithdrawalOperationById(wopid),
  );
  console.log(`status after: ${j2s(wopStatus2)}`);
}

runBankWopTest.suites = ["wallet"];
