import { api } from '@/utils/request'
import type { ApiKeyRecord, ApiKeyCreateParams, ApiKeyCreateResult } from '@/types/api'

export const MAX_KEYS_PER_USER = 10

export const useApiKeyStore = defineStore('api-key', () => {
  const keys = ref<ApiKeyRecord[]>([])
  const loading = ref(false)

  const canCreate = computed(() => keys.value.length < MAX_KEYS_PER_USER)
  const keyCount = computed(() => keys.value.length)

  async function fetchMyKeys() {
    loading.value = true
    try {
      const data = await api.get<ApiKeyRecord[]>('/api/v1/me/api-keys')
      keys.value = data
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : '获取 API Key 列表失败'
      message.error(msg)
    } finally {
      loading.value = false
    }
  }

  async function createKey(params: ApiKeyCreateParams): Promise<ApiKeyCreateResult | null> {
    try {
      const data = await api.post<ApiKeyCreateResult>('/api/v1/me/api-keys', params)
      await fetchMyKeys()
      return data
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : '创建 API Key 失败'
      message.error(msg)
      return null
    }
  }

  async function toggleKey(id: number, enabled: boolean) {
    try {
      await api.patch(`/api/v1/me/api-keys/${id}/toggle`, { enabled })
      await fetchMyKeys()
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : '操作失败'
      message.error(msg)
    }
  }

  async function deleteKey(id: number) {
    try {
      await api.delete(`/api/v1/me/api-keys/${id}`)
      await fetchMyKeys()
      message.success('已删除')
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : '删除失败'
      message.error(msg)
    }
  }

  return {
    keys,
    loading,
    canCreate,
    keyCount,
    MAX_KEYS_PER_USER,
    fetchMyKeys,
    createKey,
    toggleKey,
    deleteKey,
  }
})
