import type { AdapterFn } from './types';
import type { ActivityCacheEntry } from '../schemas';

export const rwalletAdapter: AdapterFn = (ctx) => {
	const docId = `${ctx.space}:wallet:treasury`;
	const doc = ctx.syncServer.getDoc<any>(docId);
	if (!doc) return [];

	const entries: ActivityCacheEntry[] = [];

	// Watched addresses
	if (doc.watchedAddresses) {
		for (const addr of Object.values(doc.watchedAddresses) as any[]) {
			if (!addr?.address) continue;
			const ts = addr.addedAt || 0;
			if (ts < ctx.since) continue;

			entries.push({
				id: `rwallet:${ctx.space}:addr:${addr.address}`,
				moduleId: 'rwallet',
				itemType: 'address',
				title: addr.label || `${addr.address.slice(0, 8)}…`,
				summary: `Watching ${addr.chain || 'unknown'} address ${addr.address.slice(0, 12)}…`.slice(0, 280),
				url: `${ctx.baseUrl}/${ctx.space}/rwallet`,
				author: addr.addedBy || '',
				publishedAt: ts,
				reshared: false,
				syncedAt: Date.now(),
			});
		}
	}

	// Transaction annotations
	if (doc.annotations) {
		for (const ann of Object.values(doc.annotations) as any[]) {
			if (!ann?.note) continue;
			const ts = ann.createdAt || 0;
			if (ts < ctx.since) continue;

			entries.push({
				id: `rwallet:${ctx.space}:ann:${ann.txHash || ann.id}`,
				moduleId: 'rwallet',
				itemType: 'annotation',
				title: `TX annotation`,
				summary: ann.note.slice(0, 280),
				url: `${ctx.baseUrl}/${ctx.space}/rwallet`,
				author: ann.authorDid || '',
				publishedAt: ts,
				reshared: false,
				syncedAt: Date.now(),
			});
		}
	}

	return entries.sort((a, b) => b.publishedAt - a.publishedAt).slice(0, 20);
};
