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

export const rdocsAdapter: AdapterFn = (ctx) => {
	const prefix = `${ctx.space}:notes:notebooks:`;
	const nbIds = ctx.syncServer.listDocs().filter((id: string) => id.startsWith(prefix));
	const entries: ActivityCacheEntry[] = [];

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

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

			const id = `rdocs:${ctx.space}:${note.id}`;
			entries.push({
				id,
				moduleId: 'rdocs',
				itemType: 'note',
				title: note.title,
				summary: (note.contentPlain || note.summary || '').slice(0, 280),
				url: `${ctx.baseUrl}/${ctx.space}/rdocs`,
				author: note.authorId || '',
				publishedAt: ts,
				reshared: false,
				syncedAt: Date.now(),
			});
		}
	}

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