import { LETTER_MAX_BODY_CHARS, itemDefinition, itemDisplayName } from "../definitions/items.js";

export const QUESTWARD_GIFT_AUTHOR = "John Questward";
export const QUESTWARD_GIFT_ORG = "CEO of Questward";

/**
 * @param {{ displayName: string, quantity: number }} item
 */
export function formatGiftItemBullet (item)
{
	const qty = Math.max(1, item.quantity | 0);
	const name = String(item.displayName ?? "Item").trim() || "Item";
	return `• ${qty}× ${name}`;
}

/**
 * Build the gift pigeon letter body (shared by server send + editor live preview).
 * Empty custom message omits that paragraph entirely.
 * @param {{
 *   characterDisplayName: string,
 *   message?: string,
 *   items?: Array<{ displayName?: string, itemId?: number, quantity?: number }>
 * }} opts
 */
export function formatGiftLetterBody ({ characterDisplayName, message = "", items = [] })
{
	const name = String(characterDisplayName ?? "").trim() || "Adventurer";
	const custom = String(message ?? "").replace(/\r\n/g, "\n").trim();
	const lines = (items ?? []).map((row) =>
	{
		const def = row.itemId != null ? itemDefinition(row.itemId) : null;
		const displayName = row.displayName
			?? (def ? itemDisplayName({ itemId: row.itemId, quantity: row.quantity }, def) : null)
			?? def?.displayName
			?? `Item ${row.itemId ?? "?"}`;
		return formatGiftItemBullet({ displayName, quantity: row.quantity });
	});
	const itemBlock = lines.length
		? lines.join("\n")
		: "• (no items selected)";
	const parts = [`Dear ${name}`, ""];
	if (custom)
	{
		parts.push(custom, "");
	}
	parts.push(
		"The following items were added to your bank:",
		itemBlock,
		"",
		"Thank you for playing Questward."
	);
	return parts.join("\n").slice(0, LETTER_MAX_BODY_CHARS);
}
