import { getCollection, type CollectionEntry } from 'astro:content';

export type FindItem = CollectionEntry<'find'>;

export async function getAllFinds(): Promise<FindItem[]> {
  const items = await getCollection('find');
  return items.sort((a, b) => b.data.date.valueOf() - a.data.date.valueOf());
}

export async function resolveFinds(slugs: string[]): Promise<FindItem[]> {
  const all = await getCollection('find');
  const bySlug = new Map(all.map((f) => [f.id, f]));
  return slugs
    .map((s) => bySlug.get(s))
    .filter((f): f is FindItem => Boolean(f));
}

export async function recentFindsBySource(
  sourceName: string,
  limit = 5
): Promise<FindItem[]> {
  const all = await getAllFinds();
  return all.filter((f) => f.data.source === sourceName).slice(0, limit);
}
