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

// `useApi` est un auto-import Nuxt : on le stubbe globalement pour intercepter
// les appels de chargement des referentiels et controler les reponses Hydra.
const mockGet = vi.hoisted(() => vi.fn())
vi.stubGlobal('useApi', () => ({ get: mockGet }))

const { useSupplierReferentials } = await import('../useSupplierReferentials')

describe('useSupplierReferentials', () => {
    beforeEach(() => {
        mockGet.mockReset()
        mockGet.mockResolvedValue({ member: [] })
    })

    it('charge les categories filtrees sur le type FOURNISSEUR (RG-2.10)', async () => {
        await useSupplierReferentials().loadCommon()

        expect(mockGet).toHaveBeenCalledWith(
            '/categories',
            expect.objectContaining({ pagination: 'false', typeCode: 'FOURNISSEUR' }),
            expect.objectContaining({ toast: false }),
        )
    })

    it('mappe les categories en options { value: IRI, label: name, code }', async () => {
        mockGet.mockImplementation((url: string) => {
            if (url === '/categories') {
                return Promise.resolve({ member: [{ '@id': '/api/categories/9', code: 'NEGOCIANT', name: 'Négociant' }] })
            }
            return Promise.resolve({ member: [] })
        })

        const refs = useSupplierReferentials()
        await refs.loadCommon()

        expect(refs.categories.value).toEqual([{ value: '/api/categories/9', label: 'Négociant', code: 'NEGOCIANT' }])
    })

    it('ne charge ni distributeurs ni courtiers (absents du modele fournisseur)', async () => {
        await useSupplierReferentials().loadCommon()

        const urls = mockGet.mock.calls.map(c => c[0])
        expect(urls).not.toContain('/clients')
        expect(urls).toEqual(
            expect.arrayContaining(['/categories', '/sites', '/tva_modes', '/payment_delays', '/payment_types', '/banks']),
        )
    })

    it('reste resilient : un referentiel en echec n\'empeche pas les autres', async () => {
        mockGet.mockImplementation((url: string) => {
            if (url === '/categories') return Promise.reject(new Error('403'))
            if (url === '/banks') return Promise.resolve({ member: [{ '@id': '/api/banks/1', code: 'SG', label: 'Société Générale' }] })
            return Promise.resolve({ member: [] })
        })

        const refs = useSupplierReferentials()
        await refs.loadCommon()

        expect(refs.categories.value).toEqual([])
        expect(refs.banks.value).toEqual([{ value: '/api/banks/1', label: 'Société Générale' }])
    })
})
