import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { HydraCollection } from '~/shared/utils/api'
import type { Supplier } from '../useSuppliersRepository'

// `useApi` est un auto-import Nuxt : on le stubbe globalement pour intercepter
// les appels declenches par usePaginatedList (que useSuppliersRepository enveloppe)
// et controler les reponses. Meme pattern que useClientsRepository.spec.ts.
const mockGet = vi.hoisted(() => vi.fn())
vi.stubGlobal('useApi', () => ({
    get: mockGet,
    post: vi.fn(),
    put: vi.fn(),
    patch: vi.fn(),
    delete: vi.fn(),
}))

// Import APRES le stub pour que useApi soit bien resolu au top-level du module.
const { useSuppliersRepository } = await import('../useSuppliersRepository')

/** Envelope Hydra minimale (la liste reelle des membres importe peu ici). */
function makeHydra(total: number): HydraCollection<Supplier> {
    return { totalItems: total, member: [] }
}

describe('useSuppliersRepository', () => {
    beforeEach(() => {
        mockGet.mockReset()
        // 25 items → 3 pages a 10/page : permet de tester la navigation page 2.
        mockGet.mockResolvedValue(makeHydra(25))
    })

    it('cible la ressource /suppliers en page 1 par defaut', async () => {
        const repo = useSuppliersRepository()
        await repo.fetch()

        expect(mockGet).toHaveBeenLastCalledWith(
            '/suppliers',
            { page: 1, itemsPerPage: 10 },
            expect.objectContaining({ toast: false }),
        )
    })

    it('pousse les filtres du drawer (categories multi, sites, archives inclus) et retombe en page 1', async () => {
        const repo = useSuppliersRepository()
        await repo.fetch()
        await repo.goToPage(2)
        expect(repo.currentPage.value).toBe(2)

        await repo.setFilters(
            {
                search: 'acme',
                'categoryCode[]': ['NEGOCIANT', 'TRANSPORTEUR'],
                'siteId[]': ['86', '17'],
                archivedOnly: true,
            },
            { replace: true },
        )

        expect(repo.currentPage.value).toBe(1)
        expect(mockGet).toHaveBeenLastCalledWith(
            '/suppliers',
            {
                search: 'acme',
                'categoryCode[]': ['NEGOCIANT', 'TRANSPORTEUR'],
                'siteId[]': ['86', '17'],
                archivedOnly: true,
                page: 1,
                itemsPerPage: 10,
            },
            expect.objectContaining({ toast: false }),
        )
    })

    it('repasse a une query propre apres reinitialisation des filtres', async () => {
        const repo = useSuppliersRepository()
        await repo.setFilters({ search: 'acme', archivedOnly: true }, { replace: true })
        await repo.setFilters({}, { replace: true })

        expect(mockGet).toHaveBeenLastCalledWith(
            '/suppliers',
            { page: 1, itemsPerPage: 10 },
            expect.objectContaining({ toast: false }),
        )
    })
})
