import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import softwareApi from '../api/software.api'
import { getLatestStable } from '../lib/softwareUtils'
import { useLoadable } from '../composables/useLoadable'
import type { SoftwareEntry, Release } from '../lib/interfaces/software.interface'

export const useSoftwareStore = defineStore('software', () => {
  const items = ref<SoftwareEntry[]>([])
  const highlighted = ref<SoftwareEntry | null>(null)
  const { loading, error, withCache, invalidate } = useLoadable()
  const { loading: highlightedLoading, error: highlightedError, withCache: withHighlightedCache } = useLoadable(0)

  const highlightedStableRelease = computed((): Release | null => {
    if (!highlighted.value?.releases) return null
    return getLatestStable(highlighted.value.releases) ?? null
  })

  async function fetch() {
    await withCache(async () => {
      items.value = await softwareApi.index()
    })
  }

  async function fetchHighlighted() {
    await withHighlightedCache(async () => {
      highlighted.value = await softwareApi.highlighted()
    })
  }

  function findByName(name: string): SoftwareEntry | undefined {
    return items.value.find(s => s.software.name === name)
  }

  return { items, highlighted, loading, error, highlightedLoading, highlightedError, highlightedStableRelease, fetch, fetchHighlighted, findByName, invalidate }
})
