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

// On mocke ofetch : httpExternal s'appuie sur $fetch sans jamais toucher le
// reseau pendant les tests. vi.mock est hoiste par Vitest au-dessus des imports.
const mockFetch = vi.hoisted(() => vi.fn())
vi.mock('ofetch', () => ({ $fetch: mockFetch }))

describe('httpExternal', () => {
    beforeEach(() => {
        mockFetch.mockReset()
    })

    it('retourne le JSON parse renvoye par $fetch', async () => {
        mockFetch.mockResolvedValueOnce({ ok: true })

        const res = await httpExternal<{ ok: boolean }>('https://example.test/api')

        expect(res).toEqual({ ok: true })
    })

    it('transmet la query, coupe le cookie (credentials omit) et pose un timeout par defaut', async () => {
        mockFetch.mockResolvedValueOnce([])

        await httpExternal('https://example.test/search', {
            query: { q: '80000', type: 'municipality' },
        })

        expect(mockFetch).toHaveBeenCalledWith(
            'https://example.test/search',
            expect.objectContaining({
                query: { q: '80000', type: 'municipality' },
                credentials: 'omit',
                retry: 0,
                timeout: 5000,
            }),
        )
    })

    it('permet de surcharger le timeout', async () => {
        mockFetch.mockResolvedValueOnce(null)

        await httpExternal('https://example.test', { timeoutMs: 1000 })

        expect(mockFetch).toHaveBeenCalledWith(
            'https://example.test',
            expect.objectContaining({ timeout: 1000 }),
        )
    })

    it('propage l\'erreur reseau / timeout (throw)', async () => {
        mockFetch.mockRejectedValueOnce(new Error('network down'))

        await expect(httpExternal('https://example.test')).rejects.toThrow('network down')
    })
})
