import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { apiClient } from '@/api/client'
import type { ICapabilityInfo } from '@/api/types'

export const useCapabilitiesStore = defineStore('capabilities', () => {
  // --- State ---
  const capabilities = ref<ICapabilityInfo[]>([])
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // --- Getters ---
  const enabledCapabilities = computed<ICapabilityInfo[]>(() => {
    return capabilities.value.filter((c) => c.enabled)
  })

  const capabilityNames = computed<string[]>(() => {
    return capabilities.value.map((c) => c.name)
  })

  function getByName(name: string): ICapabilityInfo | undefined {
    return capabilities.value.find((c) => c.name === name)
  }

  // --- Actions ---
  async function fetchCapabilities(): Promise<void> {
    isLoading.value = true
    error.value = null

    try {
      const response = await apiClient.getCapabilities()
      capabilities.value = response.capabilities
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取能力列表失败'
      console.error('Failed to fetch capabilities:', err)
    } finally {
      isLoading.value = false
    }
  }

  return {
    // State
    capabilities,
    isLoading,
    error,
    // Getters
    enabledCapabilities,
    capabilityNames,
    getByName,
    // Actions
    fetchCapabilities,
  }
})
