import test from "node:test";
import assert from "node:assert/strict";
import { ItemId } from "../../shared/definitions/items.js";
import { CraftingItemId, tinderboxItemInstance } from "../../shared/definitions/craftingItems.js";
import { BlockType } from "../../shared/definitions/tiles.js";
import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";
import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody, marketOrderListingFee, orderCancelledLetterBody, orderExpiredLetterBody } from "../../shared/market/exchange.js";
import { formatLetterSignature, CENTRAL_EXCHANGE_ORG } from "../../shared/courier/systemLetters.js";
import { writtenOrigin, originLabel, CraftOriginVerb } from "../../shared/items/origin.js";
import { takeMarketFunds, resolveMarketSellListing } from "../../shared/market/funds.js";
import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
import { CHUNK_SIZE } from "../../shared/protocol/constants.js";

test("blank cheques cannot be listed on the marketplace", () =>
{
	const stack = { itemId: ItemId.blankCheque, quantity: 1 };
	assert.equal(canSellOnMarketplace(stack), false);
	assert.throws(
		() => assertMarketplaceSellable(stack),
		(err) => err.message === "Blank cheques cannot be sold on the marketplace."
	);
});

test("written cheques can be listed on the marketplace", () =>
{
	const stack = {
		itemId: ItemId.filledCheque,
		quantity: 1,
		instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 2 }
	};
	assert.equal(canSellOnMarketplace(stack), true);
	assert.doesNotThrow(() => assertMarketplaceSellable(stack));
});

test("normal items are marketplace sellable by default", () =>
{
	assert.equal(canSellOnMarketplace({ itemId: ItemId.apple, quantity: 3 }), true);
});

test("fully charged tinderbox can list on CE; worn cannot", () =>
{
	const fresh = {
		itemId: CraftingItemId.tinderbox,
		quantity: 1,
		instance: tinderboxItemInstance(6)
	};
	const worn = {
		itemId: CraftingItemId.tinderbox,
		quantity: 1,
		instance: tinderboxItemInstance(1)
	};
	assert.equal(canSellOnMarketplace(fresh), true);
	assert.equal(canSellOnMarketplace(worn), false);
	assert.throws(
		() => assertMarketplaceSellable(worn),
		(err) => /partially used/i.test(err.message)
	);
});

test("letters cannot be listed on the marketplace", () =>
{
	const own = {
		itemId: ItemId.letter,
		quantity: 1,
		instance: {
			kind: "letter",
			letterId: "x",
			authorCharacterId: 1,
			authorDisplayName: "Ada",
			body: "Hi",
			opened: true
		}
	};
	const received = {
		...own,
		instance: { ...own.instance, authorCharacterId: 2, authorDisplayName: "Bob" }
	};
	assert.equal(canSellOnMarketplace(own, 1), false);
	assert.equal(canSellOnMarketplace(received, 1), false);
	assert.throws(
		() => assertMarketplaceSellable(own, 1),
		(err) => /letters cannot be sold on the marketplace/i.test(err.message)
	);
});

test("midpoint trade price rounds half units deterministically", () =>
{
	assert.equal(midpointTradePrice(100, 80), 90);
	assert.equal(midpointTradePrice(101, 80), 91);
	assert.equal(midpointTradePrice(80, 100), 90);
});

test("listing fee is 3% of notional rounded up", () =>
{
	assert.equal(marketOrderListingFee(100, 1), 3);
	assert.equal(marketOrderListingFee(10, 1), 1);
	assert.equal(marketOrderListingFee(8, 2), 1);
	assert.equal(marketOrderListingFee(0, 5), 0);
});

test("cancel and expiry letters use side-specific escrow copy", () =>
{
	const buyCancel = orderCancelledLetterBody({
		side: "buy",
		itemName: "Flower",
		quantity: 1,
		escrowLabel: "coins",
		clerkName: "Ada Ledger"
	});
	assert.match(buyCancel, /buy order for 1× Flower was cancelled/);
	assert.match(buyCancel, /coins have been returned/);
	assert.doesNotMatch(buyCancel, /coins has been returned/);

	const sellCancel = orderCancelledLetterBody({
		side: "sell",
		itemName: "Apple",
		quantity: 2,
		escrowLabel: "Apple",
		clerkName: "Ada Ledger"
	});
	assert.match(sellCancel, /sell order for 2× Apple was cancelled/);
	assert.match(sellCancel, /listed goods have been returned/);

	const buyExpired = orderExpiredLetterBody({
		side: "buy",
		itemName: "Flower",
		quantity: 1,
		escrowLabel: "coins",
		clerkName: "Ada Ledger"
	});
	assert.match(buyExpired, /coins have been returned/);
});

test("market funds spend whole coin cheques and return change", () =>
{
	const slots = emptySlots();
	slots[0] = {
		itemId: ItemId.filledCheque,
		quantity: 1,
		instance: { kind: "filled-cheque", chequeId: "c1", issuerCharacterId: 1, itemId: ItemId.coins, quantity: 40 }
	};
	const paid = takeMarketFunds(slots, 25);
	assert.equal(paid.ok, true);
	assert.equal(paid.change, 15);
	assert.equal(paid.redeemedCheques.length, 1);
	assert.equal(paid.slots.every((slot) => !slot || slot.itemId !== ItemId.filledCheque), true);
});

test("written cheque sell listing locks quantity to reserved goods", () =>
{
	const listing = resolveMarketSellListing({
		itemId: ItemId.filledCheque,
		quantity: 1,
		instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 7 }
	});
	assert.equal(listing.isCheque, true);
	assert.equal(listing.itemId, ItemId.apple);
	assert.equal(listing.quantity, 7);
	assert.equal(listing.quantityLocked, true);
});

function placePlaza (worldDb)
{
	const data = createEmptyChunkData();
	data.open = true;
	data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: null };
	data.blocks[8 * CHUNK_SIZE + 10] = { typeId: BlockType.bank, state: null };
	worldDb.saveChunkVersion(0, 0, worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
}

test("sell then buy at Central Exchange matches at midpoint and pays seller by pigeon letter", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		placePlaza(harness.worldDb);
		harness.simulation.reloadWorld();

		const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Sel", lastName: "Ler" });
		const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buy", lastName: "Er" });
		const sellerBag = addCoinsToSlots(emptySlots(), 5);
		assert.equal(sellerBag.ok, true);
		sellerBag.slots[1] = { itemId: ItemId.apple, quantity: 2 };
		harness.stateDb.saveBag(seller.character_id, {
			inventory: sellerBag.slots,
			equipment: emptyEquipment(),
			vault: [],
			vaultReserved: []
		});
		const buyerBag = addCoinsToSlots(emptySlots(), 100);
		assert.equal(buyerBag.ok, true);
		harness.stateDb.saveBag(buyer.character_id, {
			inventory: buyerBag.slots,
			equipment: emptyEquipment(),
			vault: [],
			vaultReserved: []
		});

		const sellerId = harness.simulation.spawnCharacter(1, seller);
		const buyerId = harness.simulation.spawnCharacter(2, buyer);
		harness.simulation.step();

		harness.simulation.enqueue(1, {
			type: "place-market-sell",
			characterId: seller.character_id,
			slotIndex: 1,
			quantity: 2,
			minUnitPrice: 8
		});
		const sellResult = harness.simulation.step();
		assert.equal(sellResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(sellResult.events));
		assert.ok(sellResult.events.some((event) => event.type === "market-open"));

		harness.simulation.enqueue(2, {
			type: "place-market-buy",
			characterId: buyer.character_id,
			itemId: ItemId.apple,
			quantity: 2,
			maxUnitPrice: 12
		});
		const buyResult = harness.simulation.step();
		assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events));
		const trade = buyResult.events.find((event) => event.type === "market-trade");
		assert.ok(trade, JSON.stringify(buyResult.events));
		assert.equal(trade.unitPrice, 10);
		assert.equal(trade.quantity, 2);

		const buyerBagNow = harness.simulation.bagOf(buyerId);
		assert.equal((buyerBagNow.inventory ?? []).some((slot) => slot?.itemId === ItemId.apple), true);

		// Coins go to bank; letter goes to the online seller's inventory.
		for (let i = 0; i < 500; i++)
		{
			harness.advance(1000);
			harness.simulation.step();
			const sellerVault = harness.stateDb.getBag(seller.character_id);
			const sellerBag = harness.simulation.bagOf(sellerId);
			const coins = countCoinsInSlots(sellerVault.vault ?? []);
			const letter = (sellerBag?.inventory ?? []).find((slot) => slot?.itemId === ItemId.letter)
				?? (sellerVault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
			if (coins >= 20 && letter)
			{
				assert.match(letter.instance.body, /sold|filled|proceeds/i);
				assert.doesNotMatch(letter.instance.body, /Signed,/);
				assert.equal(letter.instance.authorOrganization, "Central Exchange");
				assert.ok(letter.instance.authorDisplayName);
				assert.equal(letter.origins?.[0]?.origin?.verb, "Written");
				assert.equal(letter.origins?.[0]?.origin?.displayName, letter.instance.authorDisplayName);
				assert.equal(harness.simulation.market.lastSaleFor(ItemId.apple)?.lastTradePrice, 10);
				return;
			}
		}
		assert.fail("Seller did not receive coins in vault and letter");
	}
	finally
	{ harness.close(); }
});

test("orders older than one month auto-cancel and return escrow to bank", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		placePlaza(harness.worldDb);
		harness.simulation.reloadWorld();

		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const bag = addCoinsToSlots(emptySlots(), 50);
		assert.equal(bag.ok, true);
		harness.stateDb.saveBag(character.character_id, {
			inventory: bag.slots,
			equipment: emptyEquipment(),
			vault: [],
			vaultReserved: []
		});
		harness.simulation.spawnCharacter(1, character);
		harness.simulation.step();

		harness.simulation.enqueue(1, {
			type: "place-market-buy",
			characterId: character.character_id,
			itemId: ItemId.apple,
			quantity: 1,
			maxUnitPrice: 10
		});
		const placed = harness.simulation.step();
		assert.equal(placed.events.some((event) => event.type === "command-error"), false, JSON.stringify(placed.events));
		const open = harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id);
		assert.equal(open.length, 1);

		const order = open[0];
		harness.stateDb.db.prepare("UPDATE market_orders SET created_at = ? WHERE order_id = ?")
			.run(Date.now() - MARKET_ORDER_MAX_AGE_MS - 1000, order.orderId);

		const expired = harness.simulation.market.step(Date.now());
		assert.ok(expired.some((event) => event.type === "market-order-expired"));
		assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id).length, 0);

		for (let i = 0; i < 500; i++)
		{
			harness.advance(1000);
			harness.simulation.step();
			const vault = harness.stateDb.getBag(character.character_id);
			const bag = harness.simulation.bagOf(1);
			const coins = countCoinsInSlots(vault.vault ?? []);
			const letter = (bag?.inventory ?? []).find((slot) => slot?.itemId === ItemId.letter)
				?? (vault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
			if (coins >= 10 && letter)
			{
				assert.match(letter.instance.body, /one month/i);
				assert.doesNotMatch(letter.instance.body, /Signed,/);
				assert.equal(letter.instance.authorOrganization, "Central Exchange");
				return;
			}
		}
		assert.fail("Expired order did not return escrow letter");
	}
	finally
	{ harness.close(); }
});

test("exchange letter instance carries Central Exchange signature fields", () =>
{
	const body = soldLetterBody({
		itemName: "Apple",
		quantity: 1,
		unitPrice: 5,
		clerkName: "Bobby Pennies"
	});
	assert.doesNotMatch(body, /Signed,/);
	assert.doesNotMatch(body, /Bobby Pennies/);
	assert.doesNotMatch(body, /Central Exchange/);
	assert.match(body, /filled at 5 coins/);
	assert.equal(
		formatLetterSignature({
			authorDisplayName: "Bobby Pennies",
			authorOrganization: CENTRAL_EXCHANGE_ORG
		}),
		"Signed:\nBobby Pennies\nCentral Exchange"
	);
	assert.equal(
		formatLetterSignature({ authorDisplayName: "The Bank" }),
		"Signed:\nThe Bank"
	);
});

test("written origin labels match letter author", () =>
{
	assert.equal(originLabel(writtenOrigin("Marge Tally")), "Written by Marge Tally");
	assert.equal(CraftOriginVerb.written, "Written");
});
