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

export const useBlogStore = defineStore('blog', () => {
  const pages = ref<WikiPageWithContent[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  const currentPage = ref<WikiPageContent | null>(null)
  const currentPageLoading = ref(false)
  const currentPageError = ref<string | null>(null)

  let _loaded = false

  async function fetchPages() {
    if (_loaded) return
    loading.value = true
    try {
      pages.value = await wikiApi.listBlogPages()
      _loaded = true
    } catch (e: any) {
      error.value = `Failed to fetch wiki data: ${e.message}`
    } finally {
      loading.value = false
    }
  }

  async function fetchPage(slug: string) {
    currentPage.value = null
    currentPageError.value = null
    currentPageLoading.value = true
    try {
      const result = await wikiApi.getBlogPage(slug)
      if (result) {
        currentPage.value = result
      } else {
        currentPageError.value = 'Post not found'
      }
    } catch (e: any) {
      currentPageError.value = e.message
    } finally {
      currentPageLoading.value = false
    }
  }

  function isNew(createdAt: string): boolean {
    return (new Date().getTime() - new Date(createdAt).getTime()) < 7 * 24 * 60 * 60 * 1000
  }

  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, currentPageLoading, currentPageError, fetchPages, fetchPage, isNew, getPermalink, getCleanPreview }
})
