import { describe, it, expect, vi, beforeEach } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'

vi.mock('@/utils/request', () => ({
  api: {
    get: vi.fn(),
    post: vi.fn(),
    put: vi.fn(),
    patch: vi.fn(),
    delete: vi.fn(),
  },
}))

import { api } from '@/utils/request'
import { useAdminApiKeyStore } from '../admin-api-key'

const emptyPage = { items: [], total: 0, page: 1, per_page: 15 }

describe('useAdminApiKeyStore', () => {
  beforeEach(() => {
    setActivePinia(createPinia())
    vi.restoreAllMocks()
  })

  describe('fetchAllKeys — 查询参数契约', () => {
    it('enabled=true 应序列化为 1（后端期望 integer 0/1）', async () => {
      vi.mocked(api.get).mockResolvedValueOnce(emptyPage)

      const store = useAdminApiKeyStore()
      store.filters.enabled = true
      await store.fetchAllKeys()

      expect(api.get).toHaveBeenCalledWith(
        '/api/v1/admin/api-keys',
        expect.objectContaining({ enabled: 1 }),
      )
    })

    it('enabled=false 应序列化为 0', async () => {
      vi.mocked(api.get).mockResolvedValueOnce(emptyPage)

      const store = useAdminApiKeyStore()
      store.filters.enabled = false
      await store.fetchAllKeys()

      expect(api.get).toHaveBeenCalledWith(
        '/api/v1/admin/api-keys',
        expect.objectContaining({ enabled: 0 }),
      )
    })

    it('enabled=undefined 应保持 undefined（不触发筛选）', async () => {
      vi.mocked(api.get).mockResolvedValueOnce(emptyPage)

      const store = useAdminApiKeyStore()
      await store.fetchAllKeys()

      expect(api.get).toHaveBeenCalledWith(
        '/api/v1/admin/api-keys',
        expect.objectContaining({ enabled: undefined }),
      )
    })

    it('username 过滤器应传递给后端', async () => {
      vi.mocked(api.get).mockResolvedValueOnce(emptyPage)

      const store = useAdminApiKeyStore()
      store.filters.username = 'testuser'
      await store.fetchAllKeys()

      expect(api.get).toHaveBeenCalledWith(
        '/api/v1/admin/api-keys',
        expect.objectContaining({ username: 'testuser' }),
      )
    })

    it('email 过滤器应传递给后端', async () => {
      vi.mocked(api.get).mockResolvedValueOnce(emptyPage)

      const store = useAdminApiKeyStore()
      store.filters.email = 'test@example.com'
      await store.fetchAllKeys()

      expect(api.get).toHaveBeenCalledWith(
        '/api/v1/admin/api-keys',
        expect.objectContaining({ email: 'test@example.com' }),
      )
    })

    it('空字符串过滤器应转换为 undefined', async () => {
      vi.mocked(api.get).mockResolvedValueOnce(emptyPage)

      const store = useAdminApiKeyStore()
      store.filters.username = ''
      store.filters.email = ''
      await store.fetchAllKeys()

      expect(api.get).toHaveBeenCalledWith(
        '/api/v1/admin/api-keys',
        expect.objectContaining({ username: undefined, email: undefined }),
      )
    })
  })

})
