const addr1 = "foo";
const addr2 = "bar";
const fee = "fee";
const percentage = 0.005;

async function deposit(account, amount, asset) {
	const response = (await fetch("http://127.0.0.1:8080/deposit", {
		method: "POST",
		headers: {
			"Content-Type": "application/json",
		},
		body: JSON.stringify({
			memo: "deposit",
			account,
			amount: amount.toString(),
			status: 'pending',
			asset,
		})
	}));
	return response.json();
}

async function trade(amount, asset, from, amount_to, asset_to, to) {
	const response = (await fetch("http://127.0.0.1:8080/tx", {
		method: "POST",
		headers: {
			"Content-Type": "application/json",
		},
		body: JSON.stringify({
			memo: "trade",
			debit: [
				{
					account: from,
					amount: amount.toString(),
					asset,
				},
				{
					account: to,
					amount: amount_to.toString(),
					asset: asset_to,
				}
			],
			credit: [
				{
					account: to,
					amount: (amount * (1 - percentage)).toString(),
					asset,
				},
				{
					account: from,
					amount: amount_to.toString(),
					asset: asset_to,
				},
				{
					account: fee,
					amount: (amount * percentage).toString(),
					asset,
				}
			],
			status: 'pending',
			asset,
		})
	}));
	return response.json();
}

async function change_status(id, s_status) {
	const response = (await fetch(`http://127.0.0.1:8080/${id}`, {
		method: "POST",
		headers: {
			"Content-Type": "application/json",
		},
		body: JSON.stringify({
			status: s_status,
			memo: `change status to ${s_status}`,
		})
	}));
	return response.json();
}

async function test() {
	let d = (await deposit(addr1, 100, "BTC"));
	console.log(await change_status(d.id, 'settled'));
	d = (await deposit(addr2, 1000000, "USD"));
	console.log(await change_status(d.id, 'settled'));

	const t = await trade(1, "BTC", addr1, 26751.11, "USD", addr2);
	console.log(t);
	console.log(await change_status(t.id, 'processing',));
	console.log(await change_status(t.id, 'settled'));
}

test()