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

export const rfilesAdapter: AdapterFn = (ctx) => {
	const prefix = `${ctx.space}:files:cards:`;
	const cardIds = ctx.syncServer.listDocs().filter((id: string) => id.startsWith(prefix));
	const entries: ActivityCacheEntry[] = [];

	for (const cardDocId of cardIds) {
		const doc = ctx.syncServer.getDoc<any>(cardDocId);
		if (!doc) continue;

		// Media files
		if (doc.files) {
			for (const file of Object.values(doc.files) as any[]) {
				if (!file?.originalFilename && !file?.title) continue;
				const ts = file.createdAt || file.updatedAt || 0;
				if (ts < ctx.since) continue;

				entries.push({
					id: `rfiles:${ctx.space}:file:${file.id}`,
					moduleId: 'rfiles',
					itemType: 'file',
					title: file.title || file.originalFilename,
					summary: (file.description || `${file.mimeType || 'file'} upload`).slice(0, 280),
					url: `${ctx.baseUrl}/${ctx.space}/rfiles`,
					author: file.uploadedBy || '',
					publishedAt: ts,
					reshared: false,
					syncedAt: Date.now(),
				});
			}
		}

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

				entries.push({
					id: `rfiles:${ctx.space}:card:${card.id}`,
					moduleId: 'rfiles',
					itemType: 'memory-card',
					title: card.title,
					summary: (card.body || '').slice(0, 280),
					url: `${ctx.baseUrl}/${ctx.space}/rfiles`,
					author: card.createdBy || '',
					publishedAt: ts,
					reshared: false,
					syncedAt: Date.now(),
				});
			}
		}
	}

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