import { site } from '$lib/lexicons';
import type { Main as PublicationRecord } from '$lib/lexicons/site/standard/publication';
import type { AtUriString } from '@atproto/lex';
import type { Publication } from '$lib/types';
import { cache, HOUR_MS } from '$lib/server/cache';
import { blobUrl, createClient, getRepoInfo, repoId } from './client';

export async function fetchPublications(): Promise<Publication[]> {
	const cached = cache.get('publications');
	if (cached) {
		return cached as Publication[];
	}

	const repo = getRepoInfo('Writing section');
	if (!repo) return [];

	try {
		const client = createClient(repo.pds);
		const res = await client.list(site.standard.publication, {
			repo: repoId(repo.did),
			limit: 50
		});
		const records = res.records as ReadonlyArray<{ value: PublicationRecord; uri: AtUriString }>;

		const publications: Publication[] = records
			//Sorry flo <3, just wanting to show my writings
			.filter((x) => !x.uri.includes('blento.self'))
			.map((x) => ({
				uri: x.uri,
				name: x.value.name,
				description: x.value.description ?? '',
				href: x.value.url,
				image: x.value.icon ? blobUrl(repo.pds, repo.did, x.value.icon) : null
			}));

		cache.setWithExpiry('publications', publications, HOUR_MS);
		return publications;
	} catch (error) {
		console.warn('Failed to fetch publications:', error);
		return [];
	}
}
