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

export const rsocialsAdapter: AdapterFn = (ctx) => {
	const docId = `${ctx.space}:socials:data`;
	const doc = ctx.syncServer.getDoc<any>(docId);
	if (!doc) return [];

	const entries: ActivityCacheEntry[] = [];

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

			entries.push({
				id: `rsocials:${ctx.space}:thread:${thread.id}`,
				moduleId: 'rsocials',
				itemType: 'thread',
				title: thread.title,
				summary: (thread.tweets?.[0] || '').slice(0, 280),
				url: `${ctx.baseUrl}/${ctx.space}/rsocials`,
				author: thread.handle || '',
				publishedAt: ts,
				reshared: false,
				syncedAt: Date.now(),
			});
		}
	}

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

			const platforms = (campaign.platforms || []).join(', ');
			entries.push({
				id: `rsocials:${ctx.space}:campaign:${campaign.id}`,
				moduleId: 'rsocials',
				itemType: 'campaign',
				title: campaign.title,
				summary: (`${campaign.description || ''} — ${platforms}`).slice(0, 280),
				url: `${ctx.baseUrl}/${ctx.space}/rsocials`,
				author: '',
				publishedAt: ts,
				reshared: false,
				syncedAt: Date.now(),
			});
		}
	}

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