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

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

	const entries: ActivityCacheEntry[] = [];

	// Shared albums
	if (doc.sharedAlbums) {
		for (const album of Object.values(doc.sharedAlbums) as any[]) {
			if (!album?.name) continue;
			const ts = album.sharedAt || 0;
			if (ts < ctx.since) continue;

			entries.push({
				id: `rphotos:${ctx.space}:album:${album.id || album.name}`,
				moduleId: 'rphotos',
				itemType: 'album',
				title: album.name,
				summary: (album.description || `Shared album: ${album.name}`).slice(0, 280),
				url: `${ctx.baseUrl}/${ctx.space}/rphotos`,
				author: album.sharedBy || '',
				publishedAt: ts,
				reshared: false,
				syncedAt: Date.now(),
			});
		}
	}

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

			entries.push({
				id: `rphotos:${ctx.space}:ann:${ann.assetId || ann.id}`,
				moduleId: 'rphotos',
				itemType: 'photo-annotation',
				title: 'Photo annotation',
				summary: ann.note.slice(0, 280),
				url: `${ctx.baseUrl}/${ctx.space}/rphotos`,
				author: ann.authorDid || '',
				publishedAt: ts,
				reshared: false,
				syncedAt: Date.now(),
			});
		}
	}

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