import { describe, expect, it, vi } from 'vitest'
import { BundleLoadError, createBundleLoader } from './loader'

describe('createBundleLoader', () => {
  it('loads and caches locale bundles on demand', async () => {
    const loadFn = vi
      .fn()
      .mockResolvedValueOnce({ hello: 'שלום' })
      .mockResolvedValueOnce({ hello: 'should not reload' })
    const loader = createBundleLoader(loadFn)

    const first = await loader.load('he')
    const second = await loader.load('he')

    expect(first).toEqual({ hello: 'שלום' })
    expect(second).toBe(first)
    expect(loadFn).toHaveBeenCalledTimes(1)
    expect(loader.peek('he')).toEqual({ hello: 'שלום' })
  })

  it('throws BundleLoadError when the host loader returns nothing', async () => {
    const loader = createBundleLoader(async () => undefined)
    await expect(loader.load('en', 'admin')).rejects.toBeInstanceOf(BundleLoadError)
  })
})
