/*
 This file is part of GNU Taler
 (C) 2023 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 {
  Duration,
  succeedOrThrow,
  TalerCorebankApiClient,
  TalerMerchantApi,
  TalerMerchantInstanceHttpClient,
  TalerMerchantManagementHttpClient,
} from "@gnu-taler/taler-util";
import { WalletApiOperation } from "@gnu-taler/taler-wallet-core";
import * as fs from "node:fs";
import {
  applyTimeTravelV2,
  makeTestPaymentV2,
  useSharedTestkudosEnvironment,
  withdrawViaBankV3,
} from "../harness/environments.js";
import { GlobalTestState, sh } from "../harness/harness.js";

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

  // Hack to work around odd install location of typst templates.
  // See https://bugs.gnunet.org/view.php?id=11241
  const prefix = (
    await sh(t, "merchant-config", "taler-merchant-config -s paths -o prefix")
  ).trim();
  process.env["XDG_DATA_HOME"] = `${prefix}/.local/share/`;

  console.log(`XDG_DATA_HOME: ${process.env["XDG_DATA_HOME"]}`);

  const { walletClient, bank, exchange, merchant, merchantAdminAccessToken } =
    await useSharedTestkudosEnvironment(t);

  const bankClient = new TalerCorebankApiClient(bank.baseUrl);

  await withdrawViaBankV3(t, {
    walletClient,
    bankClient,
    exchange,
    amount: "TESTKUDOS:30",
  });

  const instanceMgmtApi = new TalerMerchantManagementHttpClient(
    merchant.makeInstanceBaseUrl(),
  );
  const instanceApi = new TalerMerchantInstanceHttpClient(
    merchant.makeInstanceBaseUrl(),
  );

  {
    const reportBytes = succeedOrThrow(
      await instanceMgmtApi.getStatisticsReportPdf(
        merchantAdminAccessToken,
        "transactions",
      ),
    );
    const f = t.testDir + `/report-0.pdf`;
    fs.writeFileSync(f, Buffer.from(reportBytes));
    console.log(`written to ${f}`);
  }

  {
    const order: TalerMerchantApi.Order = {
      summary: "Test payment 1",
      amount: "TESTKUDOS:5",
      fulfillment_url: "taler://fulfillment-success/thx",
    };

    await makeTestPaymentV2(t, {
      walletClient,
      merchant,
      merchantAdminAccessToken,
      order,
    });
    await walletClient.call(
      WalletApiOperation.TestingWaitTransactionsFinal,
      {},
    );
  }

  {
    const reportBytes = succeedOrThrow(
      await instanceMgmtApi.getStatisticsReportPdf(
        merchantAdminAccessToken,
        "transactions",
      ),
    );
    const f = t.testDir + `/report-1.pdf`;
    fs.writeFileSync(f, Buffer.from(reportBytes));
    console.log(`written to ${f}`);
  }

  {
    const order: TalerMerchantApi.Order = {
      summary: "Test payment 2",
      amount: "TESTKUDOS:1",
      fulfillment_url: "taler://fulfillment-success/thx",
    };

    await makeTestPaymentV2(t, {
      walletClient,
      merchant,
      merchantAdminAccessToken,
      order,
    });
    await walletClient.call(
      WalletApiOperation.TestingWaitTransactionsFinal,
      {},
    );
  }

  {
    const reportBytes = succeedOrThrow(
      await instanceMgmtApi.getStatisticsReportPdf(
        merchantAdminAccessToken,
        "transactions",
      ),
    );
    const f = t.testDir + `/report-2.pdf`;
    fs.writeFileSync(f, Buffer.from(reportBytes));
    console.log(`written to ${f}`);
  }

  await applyTimeTravelV2(
    Duration.toMilliseconds(
      Duration.fromSpec({
        days: 2,
      }),
    ),
    {
      exchange,
      merchant,
      walletClient,
    },
  );

  {
    const order: TalerMerchantApi.Order = {
      summary: "Test payment 3",
      amount: "TESTKUDOS:0.5",
      fulfillment_url: "taler://fulfillment-success/thx",
    };

    await makeTestPaymentV2(t, {
      walletClient,
      merchant,
      merchantAdminAccessToken,
      order,
    });
    await walletClient.call(
      WalletApiOperation.TestingWaitTransactionsFinal,
      {},
    );
  }

  {
    const reportBytes = succeedOrThrow(
      await instanceMgmtApi.getStatisticsReportPdf(
        merchantAdminAccessToken,
        "transactions",
      ),
    );
    const f = t.testDir + `/report-3.pdf`;
    fs.writeFileSync(f, Buffer.from(reportBytes));
    console.log(`written to ${f}`);
  }

  {
    const reportBytes = succeedOrThrow(
      await instanceMgmtApi.listOrdersRaw(merchantAdminAccessToken, {
        mime: "text/csv",
      }),
    );
    const f = t.testDir + `/report-4.csv`;
    fs.writeFileSync(f, Buffer.from(reportBytes));
    console.log(`written to ${f}`);
  }
}

runMerchantReportsTest.suites = ["wallet", "shared-env"];
