export type InboundMessageRow = {
	key: { remoteJid: string; id: string; fromMe: boolean };
	message: Record<string, unknown>;
	pushName?: string;
	messageTimestamp?: number | Long;
};

type Long = { toNumber?: () => number };

const MAX_PER_SESSION = 200;
const buffers = new Map<string, InboundMessageRow[]>();

function jidDigits(jid: string): string {
	return jid.replace(/@.*$/, "").replace(/\D/g, "");
}

function jidMatches(a: string, b: string): boolean {
	const da = jidDigits(a);
	const db = jidDigits(b);
	if (da === db) return true;
	// Match local 8-digit TN numbers against full 216XXXXXXXX
	if (da.length === 8 && db.endsWith(da)) return true;
	if (db.length === 8 && da.endsWith(db)) return true;
	return false;
}

export function pushInbound(sessionId: string, row: InboundMessageRow): void {
	const list = buffers.get(sessionId) ?? [];
	if (list.some((m) => m.key.id === row.key.id && m.key.remoteJid === row.key.remoteJid)) {
		return;
	}
	list.unshift(row);
	if (list.length > MAX_PER_SESSION) {
		list.length = MAX_PER_SESSION;
	}
	buffers.set(sessionId, list);
}

export function listInbound(
	sessionId: string,
	jid?: string,
	limit = 50,
): InboundMessageRow[] {
	const list = buffers.get(sessionId) ?? [];
	const filtered = jid
		? list.filter((m) => jidMatches(m.key.remoteJid, jid))
		: list;
	return filtered.slice(0, limit);
}

export function clearInboundBuffer(sessionId: string): void {
	buffers.delete(sessionId);
}
