import { defineStore } from 'pinia'
import { ref } from 'vue'
import wikiApi from '../api/wiki.api'
import { isNew } from '../lib/softwareUtils'
import { useLoadable } from '../composables/useLoadable'
import type { WikiPageWithContent, WikiPageContent } from '../lib/interfaces/wiki.interface'

export const useBlogStore = defineStore('blog', () => {
  const pages = ref<WikiPageWithContent[]>([])
  const { loading, error, withCache, invalidate } = useLoadable()

  const currentPage = ref<WikiPageContent | null>(null)
  const { loading: pageLoading, error: pageError, withCache: withPageCache } = useLoadable(0)

  async function fetch() {
    await withCache(async () => {
      pages.value = await wikiApi.listBlogPages()
    })
  }

  async function fetchPage(slug: string) {
    currentPage.value = null
    await withPageCache(async () => {
      const result = await wikiApi.getBlogPage(slug)
      if (!result) throw new Error('Post not found')
      currentPage.value = result
    })
  }

  function getPermalink(path: string): string {
    const slug = path.startsWith('blog/') ? path.replace('blog/', '') : path
    return `/blog/${slug}`
  }

  function getCleanPreview(content: string): string {
    if (!content) return ''
    return content.replace(/[#*`_[\]()]/g, '').trim().slice(0, 300) + '...'
  }

  return { pages, loading, error, currentPage, pageLoading, pageError, fetch, fetchPage, isNew, getPermalink, getCleanPreview, invalidate }
})
