import {describe, it, expect, vi, afterEach} from 'vitest'
import {jwennTeksSlug} from '../oki-api'

function fakeEntry(i) {
  return {slug: `slug-${i}`}
}

describe('jwennTeksSlug (full pagination)', () => {
  const originalFetch = global.fetch

  afterEach(() => {
    global.fetch = originalFetch
    vi.restoreAllMocks()
  })

  it('walks every page instead of stopping at the first pageSize chunk', async () => {
    const pageSize = 200
    const totalRecords = 250

    let calls = 0
    global.fetch = vi.fn(async url => {
      calls++
      if (calls > 5) {
        throw new Error('too many pagination calls, likely an infinite loop')
      }

      const pageMatch = url.match(/pagination\[page]=(\d+)/)
      const page = pageMatch ? Number(pageMatch[1]) : 1
      const start = (page - 1) * pageSize
      const end = Math.min(start + pageSize, totalRecords)
      const data = Array.from({length: Math.max(end - start, 0)}, (_, i) => fakeEntry(start + i))

      return {
        ok: true,
        json: async () => ({data})
      }
    })

    const slugs = await jwennTeksSlug()

    expect(slugs).toHaveLength(totalRecords)
    expect(slugs[0]).toBe('slug-0')
    expect(slugs.at(-1)).toBe('slug-249')
    expect(global.fetch).toHaveBeenCalledTimes(2)
  })

  it('stops after a single page when there are fewer records than pageSize', async () => {
    global.fetch = vi.fn(async () => ({
      ok: true,
      json: async () => ({data: [fakeEntry(1), fakeEntry(2)]})
    }))

    const slugs = await jwennTeksSlug()

    expect(slugs).toEqual(['slug-1', 'slug-2'])
    expect(global.fetch).toHaveBeenCalledTimes(1)
  })
})
