import { acceptHMRUpdate, defineStore } from 'pinia'
import type { Ref } from 'vue'
import MarkdownIt from 'markdown-it'
import Prism from 'markdown-it-prism'
import LinkAttributes from 'markdown-it-link-attributes'
import type { Error, Post } from '~/types'

export const usePostStore = defineStore('post', () => {
  const postList = ref([]) as Ref<Post[]>
  const currentPost = ref({}) as Ref<Post>
  const errors = ref([]) as Ref<Error[]>
  const loading = ref(false) as Ref<boolean>
  const initialLoad = ref(false) as Ref<boolean>
  const router = useRouter()

  async function fetchPosts() {
    postList.value = []
    loading.value = true
    const result = await fetch('https://api.flycro.me/items/Post')
    if (!result.ok) errors.value.push({ message: 'Failed to fetch posts' })
    const data = await result.json()
    data.data.forEach((item) => {
      postList.value.push({
        title: item.title,
        slug: item.slug,
        body: item.body,
        tags: item.tags,
        user_created: item.user_created,
        date_created: item.date_created,
        status: item.status,
      })
    })
    loading.value = false
    initialLoad.value = true
  }

  async function getCurrentPostBySlug(slug: string) {
    if (postList.value.length === 0) await fetchPosts()
    const post = postList.value.find(item => item.slug === slug)
    if (post) {
      currentPost.value = post
      const md = new MarkdownIt()
      md.use(Prism)
      md.use(LinkAttributes, {
        pattern: /^https?:\/\//,
        attrs: {
          target: '_blank',
          rel: 'noopener',
        },
      })
      currentPost.value.body = md.render(currentPost.value.body)
    }
    if (currentPost.value && Object.keys(currentPost.value).length === 0 && initialLoad.value) router.push('/404')
  }

  /**
     * Changes the current name of the user and saves the one that was used
     * before.
     *
     * @param name - new name to set
     */
  /*   function setNewName(name: string) {
    if (savedName.value)
      previousNames.value.add(savedName.value)

    savedName.value = name
  } */

  return {
    fetchPosts,
    getCurrentPostBySlug,
    loading,
    initialLoad,
    postList,
    currentPost,
  }
})

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(usePostStore, import.meta.hot))
