/*
 This file is part of GNU Taler
 (C) 2020-2025 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,
  j2s,
  Logger,
  PaymentInsufficientBalanceDetails,
  PreparePayResultType,
  succeedOrThrow,
  TalerErrorCode,
  TalerMerchantInstanceHttpClient,
  TalerWireGatewayAuth,
} from "@gnu-taler/taler-util";
import { WalletApiOperation } from "@gnu-taler/taler-wallet-core";
import { CoinConfig, defaultCoinConfig } from "../harness/denomStructures.js";
import {
  createSimpleTestkudosEnvironmentV3,
  withdrawViaBankV3,
} from "../harness/environments.js";
import {
  ExchangeService,
  getTestHarnessPaytoForLabel,
  GlobalTestState,
  HarnessExchangeBankAccount,
  setupDb,
} from "../harness/harness.js";

const logger = new Logger("test-wallet-insufficient-balance.ts");

export async function runWalletInsufficientBalanceTest(t: GlobalTestState) {
  // Set up test environment

  const coinConfig: CoinConfig[] = defaultCoinConfig.map((x) => x("TESTKUDOS"));

  let {
    bankClient,
    bank,
    exchange,
    merchant,
    walletClient,
    merchantAdminAccessToken,
  } = await createSimpleTestkudosEnvironmentV3(t, coinConfig, {
    skipWireFeeCreation: true,
  });

  const dbTwo = await setupDb(t, {
    nameSuffix: "two",
  });

  const exchangeTwo = ExchangeService.create(t, {
    name: "testexchange-2",
    currency: "TESTKUDOS",
    httpPort: 9081,
    database: dbTwo.connStr,
  });

  {
    const receiverName = "Exchange2";
    const exchangeBankUsername = "exchange2";
    const exchangeBankPassword = "mypw-password";
    const exchangePaytoUri = getTestHarnessPaytoForLabel(exchangeBankUsername);
    const wireGatewayApiBaseUrl = new URL(
      `accounts/${exchangeBankUsername}/taler-wire-gateway/`,
      bank.corebankApiBaseUrl,
    ).href;

    const wireGatewayAuth: TalerWireGatewayAuth = {
      username: exchangeBankUsername,
      password: exchangeBankPassword,
    };

    const exchangeBankAccount: HarnessExchangeBankAccount = {
      wireGatewayApiBaseUrl,
      wireGatewayAuth,
      accountPaytoUri: exchangePaytoUri,
      skipWireFeeCreation: true,
    };

    await exchangeTwo.addBankAccount("1", exchangeBankAccount);

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

    exchangeTwo.addCoinConfigList(coinConfig);

    await exchangeTwo.start();
  }

  await walletClient.client.call(WalletApiOperation.InitWallet, {
    config: {
      testing: {
        skipDefaults: true,
      },
    },
  });

  t.logStep("setup-done");

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

  {
    const exc = await t.assertThrowsTalerErrorAsync(
      async () =>
        await walletClient.call(WalletApiOperation.CheckDeposit, {
          amount: "TESTKUDOS:5" as AmountString,
          depositPaytoUri: "payto://x-taler-bank/localhost/foobar",
        }),
    );

    t.assertDeepEqual(
      exc.errorDetail.code,
      TalerErrorCode.WALLET_DEPOSIT_GROUP_INSUFFICIENT_BALANCE,
    );

    const insufficientBalanceDetails: PaymentInsufficientBalanceDetails =
      exc.errorDetail.insufficientBalanceDetails;

    t.assertAmountEquals(
      insufficientBalanceDetails.balanceAvailable,
      "TESTKUDOS:9.72",
    );
    t.assertAmountEquals(
      insufficientBalanceDetails.balanceExchangeDepositable,
      "TESTKUDOS:0",
    );
  }

  t.logStep("start-p2p-push-test");

  // Now check for p2p-push

  {
    const wres2 = await withdrawViaBankV3(t, {
      amount: "TESTKUDOS:5",
      bankClient,
      exchange: exchangeTwo,
      walletClient,
    });
    await wres2.withdrawalFinishedCond;

    const exc = await t.assertThrowsTalerErrorAsync(
      async () =>
        await walletClient.call(WalletApiOperation.CheckPeerPushDebit, {
          amount: "TESTKUDOS:20" as AmountString,
        }),
    );

    const insufficientBalanceDetails: PaymentInsufficientBalanceDetails =
      exc.errorDetail.insufficientBalanceDetails;

    const perMyExchange =
      insufficientBalanceDetails.perExchange[exchange.baseUrl];

    t.assertTrue(!!perMyExchange);

    console.log(j2s(exc.errorDetail));

    t.assertAmountEquals(
      insufficientBalanceDetails.amountRequested,
      "TESTKUDOS:20",
    );
    t.assertAmountEquals(
      insufficientBalanceDetails.maxEffectiveSpendAmount,
      "TESTKUDOS:14.22",
    );
    t.assertAmountEquals(
      perMyExchange.maxEffectiveSpendAmount,
      "TESTKUDOS:9.47",
    );
  }

  // Now test for insufficient balance details with the merchant.
  // The merchant only accepts one of the exchanges.
  {
    const merchantClient = new TalerMerchantInstanceHttpClient(
      merchant.makeInstanceBaseUrl(),
    );

    const orderResp = succeedOrThrow(
      await merchantClient.createOrder(merchantAdminAccessToken, {
        order: {
          amount: "TESTKUDOS:12",
          summary: "Test",
        },
      }),
    );

    let orderStatus = succeedOrThrow(
      await merchantClient.getOrderDetails(
        merchantAdminAccessToken,
        orderResp.order_id,
      ),
    );

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

    // Make wallet pay for the order

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

    t.assertDeepEqual(res.status, PreparePayResultType.InsufficientBalance);

    const insufficientBalanceDetails: PaymentInsufficientBalanceDetails =
      res.balanceDetails;

    const perMyExchange =
      insufficientBalanceDetails.perExchange[exchange.baseUrl];

    t.assertTrue(!!perMyExchange);

    console.log(j2s(res));

    t.assertAmountEquals(
      insufficientBalanceDetails.balanceAvailable,
      "TESTKUDOS:14.57",
    );

    t.assertAmountEquals(
      insufficientBalanceDetails.balanceReceiverAcceptable,
      "TESTKUDOS:9.72",
    );

    t.assertAmountEquals(
      insufficientBalanceDetails.perExchange[exchange.baseUrl].balanceAvailable,
      "TESTKUDOS:9.72",
    );

    t.assertAmountEquals(
      insufficientBalanceDetails.perExchange[exchangeTwo.baseUrl]
        .balanceAvailable,
      "TESTKUDOS:4.85",
    );
  }
}

runWalletInsufficientBalanceTest.suites = ["wallet"];
