import { findSlugInArray } from '@/utils/slug'
import { getAllPostsMeta } from '@/lib/posts'

/**
 * Retrieves all unique tags from the posts and counts the number of posts for each tag.
 * @returns An object where keys are tag names and values are the count of posts for that tag.
 */
export function getAllTags(): Record<string, number> {
  const posts = getAllPostsMeta()
  const tags = {} as Record<string, number>

  posts.forEach((post) => {
    const tagsArray = post.tags || []
    tagsArray.forEach((tag) => {
      tags[tag] = (tags[tag] || 0) + 1
    })
  })

  return tags
}

/**
 * Finds a tag by its slug.
 * @param tagSlug - The slug of the tag to find.
 * @returns The original tag name if found, otherwise null.
 */
export function getTagBySlug(tagSlug: string): string | null {
  const tags = getAllTags()
  return findSlugInArray(tagSlug, Object.keys(tags))
}

/**
 * Retrieves all posts that belong to a specific tag.
 * @param tagSlug - The slug of the tag to filter posts by.
 * @returns An array of posts that belong to the specified tag.
 */
export function getPostsByTag(tagSlug: string) {
  const tags = getAllTags()
  const tag = findSlugInArray(tagSlug, Object.keys(tags))

  if (!tag) {
    return []
  }

  return getAllPostsMeta().filter((post) => post.tags?.includes(tag))
}
