import { api } from '@/utils/request'
import type { PaginatedData, ApiKeyRecord, AdminApiKeyFilters } from '@/types/api'

export const useAdminApiKeyStore = defineStore('admin-api-key', () => {
  const keys = ref<ApiKeyRecord[]>([])
  const loading = ref(false)
  const pagination = reactive({
    page: 1,
    per_page: 15,
    total: 0,
  })
  const filters = reactive<AdminApiKeyFilters>({
    username: undefined,
    email: undefined,
    enabled: undefined,
  })

  async function fetchAllKeys() {
    loading.value = true
    try {
      const data = await api.get<PaginatedData<ApiKeyRecord>>('/api/v1/admin/api-keys', {
        page: pagination.page,
        per_page: pagination.per_page,
        username: filters.username || undefined,
        email: filters.email || undefined,
        enabled: filters.enabled === undefined ? undefined : filters.enabled ? 1 : 0,
      })
      keys.value = data.items
      pagination.total = data.total
      pagination.page = data.page
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : '获取 API Key 列表失败'
      message.error(msg)
    } finally {
      loading.value = false
    }
  }

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

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

  function resetFilters() {
    filters.username = undefined
    filters.email = undefined
    filters.enabled = undefined
    pagination.page = 1
  }

  return {
    keys,
    loading,
    pagination,
    filters,
    fetchAllKeys,
    toggleKey,
    deleteKey,
    resetFilters,
  }
})
