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

import { fetchWikiPage, fetchWikiPageByTitle, fetchWikiPages } from '@/lib/wiki'

const api = vi.hoisted (() => ({
  apiGet: vi.fn (),
}))

vi.mock ('@/lib/api', () => api)

describe ('wiki API functions', () => {
  beforeEach (() => {
    vi.clearAllMocks ()
  })

  it ('fetches wiki index and show pages with expected parameters', async () => {
    api.apiGet.mockResolvedValueOnce ([])
    api.apiGet.mockResolvedValueOnce ({ id: 1 })

    await fetchWikiPages ({ title: '虹' })
    await fetchWikiPage ('1', { version: '3' })

    expect (api.apiGet).toHaveBeenNthCalledWith (
        1,
        '/wiki',
        { params: { title: '虹' } },
    )
    expect (api.apiGet).toHaveBeenNthCalledWith (
        2,
        '/wiki/1',
        { params: { version: '3' } },
    )
  })

  it ('encodes title path segments and returns null on misses', async () => {
    api.apiGet.mockResolvedValueOnce ({ id: 2 })
    api.apiGet.mockRejectedValueOnce (new Error ('missing'))

    await fetchWikiPageByTitle ('a/b c', { version: undefined })
    await expect (fetchWikiPageByTitle ('missing', {})).resolves.toBeNull ()

    expect (api.apiGet).toHaveBeenNthCalledWith (
        1,
        '/wiki/title/a%2Fb%20c',
        { params: { version: undefined } },
    )
  })
})
