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

export const rnotesAdapter: AdapterFn = (ctx) => {
	const prefix = `${ctx.space}:rnotes:vaults:`;
	const vaultIds = ctx.syncServer.listDocs().filter((id: string) => id.startsWith(prefix));
	const entries: ActivityCacheEntry[] = [];

	for (const vaultDocId of vaultIds) {
		const doc = ctx.syncServer.getDoc<any>(vaultDocId);
		if (!doc?.notes) continue;

		for (const note of Object.values(doc.notes) as any[]) {
			if (!note?.path) continue;
			const ts = note.lastModifiedAt || 0;
			if (ts < ctx.since) continue;

			const id = `rnotes:${ctx.space}:${note.path}`;
			entries.push({
				id,
				moduleId: 'rnotes',
				itemType: 'vault-note',
				title: note.title || note.path.split('/').pop() || note.path,
				summary: `Vault note: ${note.path}`.slice(0, 280),
				url: `${ctx.baseUrl}/${ctx.space}/rnotes`,
				author: '',
				publishedAt: ts,
				reshared: false,
				syncedAt: Date.now(),
			});
		}
	}

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