/*
 This file is part of GNU Taler
 (C) 2024 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 {
  AccountKycStatus,
  codecForAccountKycStatus,
  codecForKycProcessClientInformation,
  Configuration,
  Duration,
  encodeCrock,
  getRandomBytes,
  hashNormalizedPaytoUri,
  j2s,
  LimitOperationType,
  succeedOrThrow,
  TalerProtocolDuration,
  TalerProtocolTimestamp,
  TalerWireGatewayHttpClient,
  TransactionMajorState,
  TransactionMinorState,
} from "@gnu-taler/taler-util";
import { readSuccessResponseJsonOrThrow } from "@gnu-taler/taler-util/http";
import {
  createSyncCryptoApi,
  WalletApiOperation,
} from "@gnu-taler/taler-wallet-core";
import {
  configureCommonKyc,
  createKycTestkudosEnvironment,
  postAmlDecision,
  withdrawViaBankV3,
} from "../harness/environments.js";
import {
  getTestHarnessPaytoForLabel,
  GlobalTestState,
  harnessHttpLib,
  waitMs,
} from "../harness/harness.js";

function adjustExchangeConfig(config: Configuration) {
  configureCommonKyc(config);

  config.setString("KYC-RULE-R1", "operation_type", "withdraw");
  config.setString("KYC-RULE-R1", "enabled", "yes");
  config.setString("KYC-RULE-R1", "exposed", "yes");
  config.setString("KYC-RULE-R1", "is_and_combinator", "no");
  config.setString("KYC-RULE-R1", "threshold", "TESTKUDOS:100");
  config.setString("KYC-RULE-R1", "timeframe", "1d");
  config.setString("KYC-RULE-R1", "next_measures", "verboten");
}

/**
 * Tests for making AML decisions.
 * - Test making decisions on unknown accounts.
 * - Test making decisions with default rules.
 */
export async function runKycDecisionsTest(t: GlobalTestState) {
  // Set up test environment

  // FIXME: Reduced test environment without merchant suffices
  const {
    walletClient,
    bankClient,
    bank,
    exchange,
    amlKeypair,
    exchangeBankAccount,
  } = await createKycTestkudosEnvironment(t, { adjustExchangeConfig });

  const merchantPayto = getTestHarnessPaytoForLabel("merchant-default");

  await bankClient.registerAccountExtended({
    name: "merchant-default",
    password: encodeCrock(getRandomBytes(32)),
    username: "merchant-default",
    payto_uri: merchantPayto,
  });

  const cryptoApi = createSyncCryptoApi();

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

  const merchantPair = await cryptoApi.createEddsaKeypair({});

  const sigResp = await cryptoApi.signWalletKycAuth({
    accountPriv: merchantPair.priv,
    accountPub: merchantPair.pub,
  });

  const kycPaytoHash = encodeCrock(hashNormalizedPaytoUri(merchantPayto));

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

  await wres.withdrawalFinishedCond;

  // Make a decision where the exchange doesn't know the account yet.
  await postAmlDecision(t, {
    amlPriv: amlKeypair.priv,
    amlPub: amlKeypair.pub,
    exchangeBaseUrl: exchange.baseUrl,
    paytoHash: kycPaytoHash,
    paytoUri: merchantPayto,
    newRules: {
      expiration_time: TalerProtocolTimestamp.now(),
      custom_measures: {},
      // Strict rules for this particular merchant!
      rules: [
        {
          operation_type: LimitOperationType.deposit,
          display_priority: 1,
          exposed: true,
          measures: ["verboten"],
          threshold: "TESTKUDOS:10",
          timeframe: Duration.toTalerProtocolDuration(
            Duration.fromSpec({
              days: 1,
            }),
          ),
        },
        {
          operation_type: LimitOperationType.withdraw,
          display_priority: 1,
          exposed: true,
          measures: ["verboten"],
          threshold: "TESTKUDOS:0",
          timeframe: Duration.toTalerProtocolDuration(
            Duration.fromSpec({
              days: 1,
            }),
          ),
        },
        {
          operation_type: LimitOperationType.balance,
          display_priority: 1,
          exposed: true,
          measures: ["verboten"],
          threshold: "TESTKUDOS:1000",
          timeframe: TalerProtocolDuration.forever(),
        },
      ],
    },
  });

  const dgRes = await walletClient.call(WalletApiOperation.CreateDepositGroup, {
    amount: "TESTKUDOS:15",
    depositPaytoUri: merchantPayto,
    testingFixedPriv: merchantPair.priv,
  });

  await walletClient.call(WalletApiOperation.TestingWaitTransactionState, {
    transactionId: dgRes.transactionId,
    txState: {
      major: TransactionMajorState.Pending,
      minor: TransactionMinorState.KycAuthRequired,
    },
  });

  succeedOrThrow(
    await wireGatewayApiClient.addKycAuth({
      auth: bank.getAdminAuth(),
      body: {
        amount: "TESTKUDOS:0.1",
        debit_account: merchantPayto,
        account_pub: merchantPair.pub,
      },
    }),
  );

  let checkResp: AccountKycStatus | undefined;

  while (1) {
    let checkHttpResp = await harnessHttpLib.fetch(
      new URL(`kyc-check/${kycPaytoHash}`, exchange.baseUrl).href,
      {
        headers: {
          ["Account-Owner-Signature"]: sigResp.sig,
        },
      },
    );

    console.log(`status: ${checkHttpResp.status}`);

    if (checkHttpResp.status == 409 || checkHttpResp.status == 404) {
      await waitMs(200);
      continue;
    }

    checkResp = await readSuccessResponseJsonOrThrow(
      checkHttpResp,
      codecForAccountKycStatus(),
    );

    break;
  }

  t.assertTrue(!!checkResp);

  console.log(j2s(checkResp));

  let infoHttpResp = await harnessHttpLib.fetch(
    new URL(`kyc-info/${checkResp.access_token}`, exchange.baseUrl).href,
  );
  t.assertDeepEqual(infoHttpResp.status, 200);
  const infoResp = await readSuccessResponseJsonOrThrow(
    infoHttpResp,
    codecForKycProcessClientInformation(),
  );

  console.log(j2s(infoResp));
}

runKycDecisionsTest.suites = ["wallet"];
