import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import softwareApi from '../api/software.api'
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 = ref(false)
  const error = ref<string | null>(null)
  let _loaded = false

  const highlightedStableRelease = computed(() => {
    if (!highlighted.value?.releases) return null
    const stable = highlighted.value.releases
      .filter((r: Release) => !r.version.startsWith('dev-'))
      .sort((a: Release, b: Release) => new Date(b.UpdatedAt).getTime() - new Date(a.UpdatedAt).getTime())
    return stable[0] ?? null
  })

  async function fetchAll() {
    if (_loaded) return
    loading.value = true
    try {
      items.value = await softwareApi.index()
      _loaded = true
    } catch (e: any) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

  async function fetchHighlighted() {
    try {
      highlighted.value = await softwareApi.highlighted()
    } catch (e) {
      console.error('Failed to fetch highlighted software:', e)
    }
  }

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

  function getLatestStable(releases: Release[]): Release {
    return releases
      .filter(r => !r.version.startsWith('dev-'))
      .sort((a, b) => new Date(b.UpdatedAt).getTime() - new Date(a.UpdatedAt).getTime())[0]
  }

  return { items, highlighted, loading, error, highlightedStableRelease, fetchAll, fetchHighlighted, findByName, getLatestStable }
})
