import { ref } from 'vue'
import { http } from '@/api'
import { CACHE_KEYS, cachedFetch } from '@/composables/useCachedQuery'

export interface ServerCategoryOption {
  /** API value: `` for all, ``uncategorized`` for empty category */
  name: string
  label: string
  count: number
}

export function categoryDisplayLabel(name: string): string {
  return name === 'uncategorized' ? '未分类' : name
}

export function useServerCategories() {
  const categories = ref<ServerCategoryOption[]>([])
  const loading = ref(false)
  const totalCount = ref(0)

  async function loadCategories(silent = false) {
    if (!silent) loading.value = true
    try {
      const { data: res } = await cachedFetch(
        CACHE_KEYS.serverCategories,
        () => http.get<{ categories: { name: string; count: number }[] }>('/servers/categories'),
      )
      const items = res.categories || []
      totalCount.value = items.reduce((sum, c) => sum + (c.count || 0), 0)
      categories.value = items
        .map(c => ({
          name: c.name,
          label: categoryDisplayLabel(c.name),
          count: c.count,
        }))
        .sort((a, b) => {
          if (a.name === 'uncategorized') return 1
          if (b.name === 'uncategorized') return -1
          return a.label.localeCompare(b.label, 'zh')
        })
    } catch {
      categories.value = []
      totalCount.value = 0
    } finally {
      if (!silent) loading.value = false
    }
  }

  return { categories, loading, totalCount, loadCategories }
}
