/*
 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 {
  AccessToken,
  CharityRequest,
  DonauHttpClient,
  encodeCrock,
  getRandomBytes,
  j2s,
  succeedOrThrow,
} from "@gnu-taler/taler-util";
import { defaultCoinConfig } from "../harness/denomStructures.js";
import { DonauService } from "../harness/harness-donau.js";
import { GlobalTestState, setupDb } from "../harness/harness.js";

/**
 * Test endpoints for DONAU charity management.
 */
export async function runDonauCharityManagementTest(t: GlobalTestState) {
  // Set up test environment

  const db = await setupDb(t);

  const donau = DonauService.create(t, {
    currency: "TESTKUDOS",
    database: db.connStr,
    httpPort: 8084,
    name: "donau",
    domain: "Bern",
  });

  donau.addCoinConfigList(defaultCoinConfig.map((x) => x("TESTKUDOS")));

  await donau.start();

  const donauClient = new DonauHttpClient(donau.baseUrl);

  const config = await donauClient.getConfig();
  console.log(`config: ${j2s(config)}`);

  const keys = await donauClient.getKeys();
  console.log(`keys: ${j2s(keys)}`);

  const merchantPub = encodeCrock(getRandomBytes(32));

  const tok: AccessToken = "secret-token:secret" as AccessToken;

  const createBody = {
    charity_name: "Test",
    charity_pub: merchantPub,
    charity_url: "http://example.localhost/",
    current_year: new Date().getFullYear(),
    max_per_year: "TESTKUDOS:100",
    receipts_to_date: "TESTKUDOS:0",
  } satisfies CharityRequest;

  succeedOrThrow(await donauClient.createCharity(tok, createBody));

  const charityList = succeedOrThrow(await donauClient.getCharities(tok));
  console.log(j2s(charityList));

  // Check for idempotency
  succeedOrThrow(await donauClient.createCharity(tok, createBody));
}

runDonauCharityManagementTest.suites = ["donau"];
