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

export const rtasksAdapter: AdapterFn = (ctx) => {
	const prefix = `${ctx.space}:tasks:boards:`;
	const boardIds = ctx.syncServer.listDocs().filter((id: string) => id.startsWith(prefix));
	const entries: ActivityCacheEntry[] = [];

	for (const boardDocId of boardIds) {
		const doc = ctx.syncServer.getDoc<any>(boardDocId);
		if (!doc?.tasks) continue;

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

			const id = `rtasks:${ctx.space}:${task.id}`;
			const status = task.status ? ` [${task.status}]` : '';
			const priority = task.priority ? ` (${task.priority})` : '';
			entries.push({
				id,
				moduleId: 'rtasks',
				itemType: 'task',
				title: task.title,
				summary: (`${task.description || ''}${status}${priority}`).slice(0, 280),
				url: `${ctx.baseUrl}/${ctx.space}/rtasks`,
				author: task.createdBy || '',
				publishedAt: ts,
				reshared: false,
				syncedAt: Date.now(),
			});
		}
	}

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