import { computed } from 'vue'
import { useProfileSession } from './useProfileSession'

const ROLE_HIERARCHY: Record<string, string[]> = {
  ROLE_ADMIN: ['ROLE_ADMIN', 'ROLE_GESTIONNAIRE', 'ROLE_VIEWER', 'ROLE_USER'],
  ROLE_GESTIONNAIRE: ['ROLE_GESTIONNAIRE', 'ROLE_VIEWER', 'ROLE_USER'],
  ROLE_VIEWER: ['ROLE_VIEWER', 'ROLE_USER'],
  ROLE_USER: ['ROLE_USER'],
}

export function usePermissions() {
  const { activeProfile } = useProfileSession()

  const effectiveRoles = computed<string[]>(() => {
    const roles = (activeProfile.value?.roles as string[] | undefined) ?? ['ROLE_USER']
    const all = new Set<string>()
    for (const role of roles) {
      const inherited = ROLE_HIERARCHY[role] ?? [role]
      for (const r of inherited) {
        all.add(r)
      }
    }
    return [...all]
  })

  const isGranted = (role: string): boolean => {
    return effectiveRoles.value.includes(role)
  }

  const isAdmin = computed(() => isGranted('ROLE_ADMIN'))
  const canEdit = computed(() => isGranted('ROLE_GESTIONNAIRE'))
  const canView = computed(() => isGranted('ROLE_VIEWER'))

  return {
    isAdmin,
    canEdit,
    canView,
    isGranted,
    effectiveRoles,
  }
}
