import type {
  ContentCache,
  ContentItem,
  ContentSource,
  WordpressCategory,
  WordpressPage,
  WordpressPost,
} from "./types";

export function newestItems(
  cache: ContentCache,
  limit: number,
  sources?: ContentSource[],
): ContentItem[] {
  const items = sources ? cache.items.filter((i) => sources.includes(i.source)) : cache.items;
  return [...items]
    .sort((a, b) => Date.parse(b.publishedAt) - Date.parse(a.publishedAt))
    .slice(0, Math.max(0, limit));
}

export function youtubeVideos(cache: ContentCache): ContentItem[] {
  return cache.items.filter((i) => i.source === "youtube");
}

export function podcastEpisodes(cache: ContentCache): ContentItem[] {
  return cache.items.filter((i) => i.source === "podcast");
}

export function instagramPosts(cache: ContentCache): ContentItem[] {
  return cache.items.filter((i) => i.source === "instagram");
}

export function highPerformingYoutubeVideos(
  cache: ContentCache,
  limit: number,
  curatedIds: string[],
): ContentItem[] {
  const videos = youtubeVideos(cache);

  // If we have a curated list, it wins (keeps the page stable even without metrics).
  if (curatedIds.length > 0) {
    const byId = new Map(videos.map((v) => [v.id, v]));
    return curatedIds
      .map((id) => byId.get(id))
      .filter(Boolean)
      .slice(0, Math.max(0, limit)) as ContentItem[];
  }

  // Otherwise rank by views where possible.
  const ranked = [...videos].sort((a, b) => (b.metrics?.views || 0) - (a.metrics?.views || 0));
  return ranked.slice(0, Math.max(0, limit));
}

export function wordpressPosts(cache: ContentCache): WordpressPost[] {
  const posts = cache.wordpress?.posts || [];
  return [...posts].sort((a, b) => Date.parse(b.publishedAt) - Date.parse(a.publishedAt));
}

export function wordpressPages(cache: ContentCache): WordpressPage[] {
  const pages = cache.wordpress?.pages || [];
  return [...pages].sort((a, b) => Date.parse(b.publishedAt) - Date.parse(a.publishedAt));
}

export function wordpressCategories(cache: ContentCache): WordpressCategory[] {
  const cats = cache.wordpress?.categories || [];
  return [...cats].sort((a, b) => a.name.localeCompare(b.name));
}

export function wordpressPostBySlug(cache: ContentCache, slug: string): WordpressPost | undefined {
  return (cache.wordpress?.posts || []).find((p) => p.slug === slug);
}

export function wordpressPageBySlug(cache: ContentCache, slug: string): WordpressPage | undefined {
  return (cache.wordpress?.pages || []).find((p) => p.slug === slug);
}

export function wordpressPostsByCategorySlug(cache: ContentCache, categorySlug: string): WordpressPost[] {
  const cats = cache.wordpress?.categories || [];
  const category = cats.find((c) => c.slug === categorySlug);
  if (!category) return [];
  return wordpressPosts(cache).filter((p) => p.categoryIds.includes(category.id));
}
