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

export const rcalAdapter: AdapterFn = (ctx) => {
	const docId = `${ctx.space}:cal:events`;
	const doc = ctx.syncServer.getDoc<any>(docId);
	if (!doc?.events) return [];

	const entries: ActivityCacheEntry[] = [];
	for (const evt of Object.values(doc.events) as any[]) {
		if (!evt?.title) continue;
		const ts = evt.createdAt || evt.startTime || 0;
		if (ts < ctx.since) continue;

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

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