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

export const useHowtosStore = defineStore('howtos', () => {
  const pages = ref<WikiPage[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  let _loaded = false

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

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

  return { pages, loading, error, fetchPages, isNew }
})
