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 { dyeItemInstance } from "../../shared/definitions/dyes.js";
import { potionItemInstance } from "../../shared/alchemy/recipes.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 {
	buildMarketCatalogEntries,
	marketOrdersCompatible,
	recipeListingKey,
	recipePaperDisplayName,
	potionListingKey,
	flowerListingKey,
	arrowListingKey,
	UNSTABLE_POTION_LISTING_KEY,
	listingKeyFromStack
} from "../../shared/market/listingKey.js";
import { alchemyPotionDefinition } from "../../shared/definitions/alchemy.js";
import { MagicElement } from "../../shared/definitions/attackTypes.js";
import { RangedItemId } from "../../shared/definitions/rangedItems.js";
import { ClothItemId } from "../../shared/definitions/clothItems.js";
import { FlowerColorId, flowerItemInstance } from "../../shared/definitions/dyes.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("full potions and dyes can list on CE; sipped or used cannot", () =>
{
	const fullPotion = {
		itemId: ItemId.potion,
		quantity: 1,
		instance: potionItemInstance({
			potionKey: "lesserHealthTonic",
			displayName: "Lesser health tonic",
			color: { r: 0.95, g: 0.38, b: 0.32 },
			fillLevel: 4,
			effect: { type: "health-regen", amountPerSecond: 1, durationMs: 10_000 },
			effectKey: "health-regen"
		})
	};
	const sipped = {
		...fullPotion,
		instance: { ...fullPotion.instance, fillLevel: 3 }
	};
	const fullDye = {
		itemId: ItemId.dye,
		quantity: 1,
		instance: dyeItemInstance({ r: 0.8, g: 0.1, b: 0.1 }, 4)
	};
	const usedDye = {
		itemId: ItemId.dye,
		quantity: 1,
		instance: dyeItemInstance({ r: 0.8, g: 0.1, b: 0.1 }, 2)
	};
	const unstableFull = {
		itemId: ItemId.potion,
		quantity: 1,
		instance: potionItemInstance({
			potionKey: "unstable:glow",
			unstable: true,
			displayName: "Unstable draught",
			color: { r: 0.95, g: 0.9, b: 0.45 },
			fillLevel: 3,
			effectKey: "glow",
			effect: { type: "glow", lightRadiusTiles: 2, durationMs: 10_000 }
		})
	};
	const unstableSipped = {
		...unstableFull,
		instance: { ...unstableFull.instance, fillLevel: 2 }
	};
	assert.equal(canSellOnMarketplace(fullPotion), true);
	assert.equal(canSellOnMarketplace(sipped), false);
	assert.equal(canSellOnMarketplace(fullDye), true);
	assert.equal(canSellOnMarketplace(usedDye), false);
	assert.equal(canSellOnMarketplace(unstableFull), true);
	assert.equal(canSellOnMarketplace(unstableSipped), false);
});

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));
}

function recipePaperStack (potionKey, displayName)
{
	return {
		itemId: ItemId.recipePaper,
		quantity: 1,
		instance: {
			kind: "recipe-paper",
			recipeId: `test-${potionKey}`,
			potionKey,
			displayName: displayName ?? recipePaperDisplayName(potionKey)
		}
	};
}

test("market catalog lists each alchemy recipe paper separately", () =>
{
	const catalog = buildMarketCatalogEntries({
		lastSaleFor: () => null,
		undiscountedMarketCoins: (itemId) => (itemId === ItemId.recipePaper ? 5 : 10),
		now: Date.now(),
		lerpDurationMs: 0,
		settings: {}
	});
	const recipes = catalog.filter((entry) => entry.itemId === ItemId.recipePaper);
	assert.ok(recipes.length > 1);
	assert.ok(recipes.some((entry) => entry.listingKey === recipeListingKey("lesserHealthTonic")));
	assert.ok(recipes.some((entry) => entry.displayName.toLowerCase().includes("lesser health tonic")));
	assert.equal(recipes.some((entry) => !entry.listingKey), false);
});

test("market catalog lists each drinkable potion brew separately", () =>
{
	const catalog = buildMarketCatalogEntries({
		lastSaleFor: () => null,
		undiscountedMarketCoins: (itemId) => (itemId === ItemId.potion ? 7 : 10),
		now: Date.now(),
		lerpDurationMs: 0,
		settings: {}
	});
	const potions = catalog.filter((entry) => entry.itemId === ItemId.potion);
	assert.ok(potions.length > 1);
	assert.ok(potions.some((entry) => entry.listingKey === potionListingKey("lesserHealthTonic")));
	assert.ok(potions.some((entry) => entry.displayName === "Lesser health tonic"));
	assert.ok(potions.some((entry) => entry.listingKey === UNSTABLE_POTION_LISTING_KEY));
	assert.equal(potions.filter((entry) => entry.listingKey === UNSTABLE_POTION_LISTING_KEY).length, 1);
	assert.equal(potions.some((entry) => !entry.listingKey), false);
	assert.equal(potions.some((entry) => entry.displayName === "Potion"), false);
	assert.equal(
		potions.some((entry) => entry.listingKey === potionListingKey("tanningBrew")),
		true,
		"tanning brew is listed as a drinkable potion"
	);
});

test("market catalog expands flowers and tipped arrows", () =>
{
	const catalog = buildMarketCatalogEntries({
		lastSaleFor: () => null,
		undiscountedMarketCoins: () => 4,
		now: Date.now(),
		lerpDurationMs: 0,
		settings: {}
	});
	const flowers = catalog.filter((entry) => entry.itemId === ItemId.flower);
	assert.ok(flowers.length >= 9);
	assert.ok(flowers.every((entry) => entry.listingKey));
	assert.ok(flowers.some((entry) => entry.listingKey === flowerListingKey(FlowerColorId.red)));
	assert.ok(flowers.some((entry) => entry.displayName === "Red flower"));

	const bronze = catalog.filter((entry) => entry.itemId === RangedItemId.bronzeArrow);
	assert.ok(bronze.some((entry) => entry.listingKey == null && entry.displayName));
	assert.ok(bronze.some((entry) => entry.listingKey === arrowListingKey(MagicElement.fire)));
	assert.ok(bronze.some((entry) => /fire/i.test(entry.displayName)));
});

test("unstable and tipped-arrow stacks carry market listing keys", () =>
{
	const unstable = {
		itemId: ItemId.potion,
		quantity: 1,
		instance: potionItemInstance({
			potionKey: "unstable:glow",
			unstable: true,
			displayName: "Unstable draught",
			color: { r: 0.95, g: 0.9, b: 0.45 },
			fillLevel: 3,
			effectKey: "glow",
			effect: { type: "glow", lightRadiusTiles: 2, durationMs: 10_000 }
		})
	};
	assert.equal(listingKeyFromStack(unstable), UNSTABLE_POTION_LISTING_KEY);
	assert.equal(
		listingKeyFromStack({
			itemId: RangedItemId.bronzeArrow,
			quantity: 5,
			instance: { kind: "tipped-arrow", element: MagicElement.fire }
		}),
		arrowListingKey(MagicElement.fire)
	);
	assert.equal(
		listingKeyFromStack({
			itemId: ItemId.flower,
			quantity: 1,
			instance: flowerItemInstance(FlowerColorId.blue)
		}),
		flowerListingKey(FlowerColorId.blue)
	);
	assert.equal(
		listingKeyFromStack({
			itemId: ClothItemId.cottonShirt,
			quantity: 1,
			instance: { kind: "clothing", dyeColor: { r: 0.2, g: 0.4, b: 0.8 } }
		}),
		null,
		"dyed clothing stays unkeyed so buyers get a colour surprise"
	);
});

test("unstable buy orders match any unstable sell effect", () =>
{
	const buy = { itemId: ItemId.potion, listingKey: UNSTABLE_POTION_LISTING_KEY };
	const glowSell = {
		itemId: ItemId.potion,
		listingKey: UNSTABLE_POTION_LISTING_KEY,
		escrowStack: {
			itemId: ItemId.potion,
			quantity: 1,
			instance: potionItemInstance({
				potionKey: "unstable:glow",
				unstable: true,
				displayName: "Unstable draught",
				fillLevel: 3,
				effectKey: "glow"
			})
		}
	};
	const shrinkSell = {
		itemId: ItemId.potion,
		listingKey: UNSTABLE_POTION_LISTING_KEY,
		escrowStack: {
			itemId: ItemId.potion,
			quantity: 1,
			instance: potionItemInstance({
				potionKey: "unstable:shrink",
				unstable: true,
				displayName: "Unstable draught",
				fillLevel: 2,
				effectKey: "shrink"
			})
		}
	};
	assert.equal(marketOrdersCompatible(buy, glowSell), true);
	assert.equal(marketOrdersCompatible(buy, shrinkSell), true);
	assert.equal(
		marketOrdersCompatible(buy, {
			itemId: ItemId.potion,
			listingKey: potionListingKey("lesserHealthTonic")
		}),
		false
	);
});

test("dyed clothing sell matches an undyed clothing buy (colour surprise)", () =>
{
	const buy = { itemId: ClothItemId.cottonShirt, listingKey: null };
	const dyedSell = {
		itemId: ClothItemId.cottonShirt,
		listingKey: null,
		escrowStack: {
			itemId: ClothItemId.cottonShirt,
			quantity: 1,
			instance: { kind: "clothing", dyeColor: { r: 0.9, g: 0.1, b: 0.2 } }
		}
	};
	const plainSell = {
		itemId: ClothItemId.cottonShirt,
		listingKey: null,
		escrowStack: { itemId: ClothItemId.cottonShirt, quantity: 1, instance: null }
	};
	assert.equal(marketOrdersCompatible(buy, dyedSell), true);
	assert.equal(marketOrdersCompatible(buy, plainSell), true);
});

test("recipe paper sell listings carry listing keys", () =>
{
	const stack = recipePaperStack("lesserHealthTonic");
	const listing = resolveMarketSellListing(stack);
	assert.ok(listing);
	assert.equal(listing.listingKey, recipeListingKey("lesserHealthTonic"));
	assert.match(listing.displayName.toLowerCase(), /lesser health tonic recipe/);
	assert.equal(listing.quantityLocked, true);
});

test("potion sell listings carry brew listing keys", () =>
{
	const potion = alchemyPotionDefinition("lesserHealthTonic");
	const stack = {
		itemId: ItemId.potion,
		quantity: 3,
		instance: potionItemInstance({
			potionKey: potion.potionKey,
			displayName: potion.displayName,
			color: potion.color,
			fillLevel: potion.fillLevel,
			effect: potion.effect,
			effectKey: potion.effect?.type
		})
	};
	const listing = resolveMarketSellListing(stack);
	assert.ok(listing);
	assert.equal(listing.listingKey, potionListingKey("lesserHealthTonic"));
	assert.equal(listing.displayName, "Lesser health tonic");
	assert.equal(listing.quantityLocked, false);
});

test("recipe paper buy and sell orders only match the same recipe", () =>
{
	const lesserBuy = {
		itemId: ItemId.recipePaper,
		listingKey: recipeListingKey("lesserHealthTonic")
	};
	const lesserSell = {
		itemId: ItemId.recipePaper,
		listingKey: recipeListingKey("lesserHealthTonic"),
		escrowStack: recipePaperStack("lesserHealthTonic")
	};
	const claritySell = {
		itemId: ItemId.recipePaper,
		listingKey: recipeListingKey("clarityPotion"),
		escrowStack: recipePaperStack("clarityPotion")
	};
	assert.equal(marketOrdersCompatible(lesserBuy, lesserSell), true);
	assert.equal(marketOrdersCompatible(lesserBuy, claritySell), false);
});

test("matching recipe paper buy and sell orders trade the specific recipe", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		placePlaza(harness.worldDb);
		harness.simulation.reloadWorld();

		const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Scribe", lastName: "One" });
		const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buyer", lastName: "Two" });
		const sellerBag = addCoinsToSlots(emptySlots(), 5);
		assert.equal(sellerBag.ok, true);
		sellerBag.slots[1] = recipePaperStack("lesserHealthTonic");
		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: []
		});

		harness.simulation.spawnCharacter(1, seller);
		harness.simulation.spawnCharacter(2, buyer);
		harness.simulation.step();

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

		harness.simulation.enqueue(2, {
			type: "place-market-buy",
			characterId: buyer.character_id,
			itemId: ItemId.recipePaper,
			listingKey: recipeListingKey("lesserHealthTonic"),
			quantity: 1,
			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.quantity, 1);

		const buyerBagNow = harness.simulation.bagOf(2);
		const recipe = (buyerBagNow.inventory ?? []).find((slot) => slot?.itemId === ItemId.recipePaper);
		assert.ok(recipe);
		assert.equal(recipe.instance?.potionKey, "lesserHealthTonic");
	}
	finally
	{ harness.close(); }
});

test("matching potion buy and sell orders trade the specific brew", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		placePlaza(harness.worldDb);
		harness.simulation.reloadWorld();

		const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Alchem", lastName: "One" });
		const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buyer", lastName: "Two" });
		const potion = alchemyPotionDefinition("lesserHealthTonic");
		const sellerBag = addCoinsToSlots(emptySlots(), 5);
		assert.equal(sellerBag.ok, true);
		sellerBag.slots[1] = {
			itemId: ItemId.potion,
			quantity: 2,
			instance: potionItemInstance({
				potionKey: potion.potionKey,
				displayName: potion.displayName,
				color: potion.color,
				fillLevel: potion.fillLevel,
				effect: potion.effect,
				effectKey: potion.effect?.type
			})
		};
		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: []
		});

		harness.simulation.spawnCharacter(1, seller);
		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));

		harness.simulation.enqueue(2, {
			type: "place-market-buy",
			characterId: buyer.character_id,
			itemId: ItemId.potion,
			listingKey: potionListingKey("lesserHealthTonic"),
			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.quantity, 2);

		const buyerBagNow = harness.simulation.bagOf(2);
		const brew = (buyerBagNow.inventory ?? []).find((slot) =>
			slot?.itemId === ItemId.potion && slot.instance?.potionKey === "lesserHealthTonic"
		);
		assert.ok(brew);
		assert.equal(brew.quantity, 2);
	}
	finally
	{ harness.close(); }
});

test("recipe paper buy orders for a different recipe do not match", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		placePlaza(harness.worldDb);
		harness.simulation.reloadWorld();

		const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
		const sellerBag = addCoinsToSlots(emptySlots(), 5);
		assert.equal(sellerBag.ok, true);
		sellerBag.slots[1] = recipePaperStack("lesserHealthTonic");
		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: []
		});

		harness.simulation.spawnCharacter(1, seller);
		harness.simulation.spawnCharacter(2, buyer);
		harness.simulation.step();

		harness.simulation.enqueue(1, {
			type: "place-market-sell",
			characterId: seller.character_id,
			slotIndex: 1,
			quantity: 1,
			minUnitPrice: 8
		});
		harness.simulation.step();

		harness.simulation.enqueue(2, {
			type: "place-market-buy",
			characterId: buyer.character_id,
			itemId: ItemId.recipePaper,
			listingKey: recipeListingKey("clarityPotion"),
			quantity: 1,
			maxUnitPrice: 12
		});
		const buyResult = harness.simulation.step();
		assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events));
		assert.equal(buyResult.events.some((event) => event.type === "market-trade"), false);
		assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(seller.character_id).length, 1);
		assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(buyer.character_id).length, 1);
	}
	finally
	{ harness.close(); }
});

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");
});
