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

// Mock du store auth : le composable ne depend que de auth.user.
const mockUser = vi.hoisted(() => ({
    value: null as { isAdmin: boolean; effectivePermissions: string[] } | null,
}))

vi.mock('~/shared/stores/auth', () => ({
    useAuthStore: () => ({
        get user() {
            return mockUser.value
        },
    }),
}))

describe('usePermissions', () => {
    beforeEach(() => {
        mockUser.value = null
    })

    it('refuse toute permission quand aucun utilisateur n\'est connecte', () => {
        const { can, canAny, canAll } = usePermissions()
        expect(can('core.users.view')).toBe(false)
        expect(canAny(['core.users.view', 'core.roles.view'])).toBe(false)
        expect(canAll(['core.users.view'])).toBe(false)
    })

    it('accorde toutes les permissions a un admin via le bypass', () => {
        mockUser.value = { isAdmin: true, effectivePermissions: [] }
        const { can, canAll } = usePermissions()
        expect(can('core.users.view')).toBe(true)
        expect(can('module.inexistante.action')).toBe(true)
        expect(canAll(['a.b.c', 'd.e.f'])).toBe(true)
    })

    it('accorde une permission presente dans effectivePermissions', () => {
        mockUser.value = { isAdmin: false, effectivePermissions: ['core.users.view'] }
        const { can } = usePermissions()
        expect(can('core.users.view')).toBe(true)
    })

    it('refuse une permission absente pour un non-admin', () => {
        mockUser.value = { isAdmin: false, effectivePermissions: ['core.users.view'] }
        const { can } = usePermissions()
        expect(can('core.roles.manage')).toBe(false)
    })

    it('canAny retourne true si au moins un code matche', () => {
        mockUser.value = { isAdmin: false, effectivePermissions: ['core.users.view'] }
        const { canAny } = usePermissions()
        expect(canAny(['core.roles.manage', 'core.users.view'])).toBe(true)
        expect(canAny(['core.roles.manage', 'core.permissions.view'])).toBe(false)
    })

    it('canAll retourne true uniquement si tous les codes matchent', () => {
        mockUser.value = {
            isAdmin: false,
            effectivePermissions: ['core.users.view', 'core.roles.view'],
        }
        const { canAll } = usePermissions()
        expect(canAll(['core.users.view', 'core.roles.view'])).toBe(true)
        expect(canAll(['core.users.view', 'core.roles.manage'])).toBe(false)
    })
})
