import { ref, computed } from 'vue'

import { HUB_URL } from 'src/config/hub'

// Singleton state — shared across all components
// DEV local (pas de hub devant pour /auth/permissions) : profil permissif d'emblée pour pouvoir prévisualiser/auditer
// toutes les pages. En PROD : null → chargé depuis le hub (restrictif tant que non chargé). Aucun effet en prod.
const _DEV_LOCAL = typeof window !== 'undefined' && (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1')
const permissions = ref(_DEV_LOCAL ? { email: 'dev@localhost', name: 'Dev (local)', is_superuser: true, capabilities: {}, groups: ['admin'] } : null) // { email, username, name, groups, is_superuser, capabilities, overrides }
const loading = ref(false)
const error = ref(null)

let fetchPromise = null // Prevent duplicate fetches

/**
 * Fetch effective permissions for the current user from targo-hub.
 * Reads X-Authentik-Email header (injected by Traefik).
 * @param {string} email — user email (from Authentik header or session)
 */
async function loadPermissions (email) {
  if (!email) return
  if (fetchPromise) return fetchPromise

  loading.value = true
  error.value = null

  fetchPromise = fetch(`${HUB_URL}/auth/permissions?email=${encodeURIComponent(email)}`)
    .then(r => {
      if (!r.ok) throw new Error('Permission fetch failed: ' + r.status)
      return r.json()
    })
    .then(data => {
      permissions.value = data
    })
    .catch(e => {
      console.error('[usePermissions]', e.message)
      error.value = e.message
      // DEV local (pas de hub devant) : le fetch échoue → on débloque l'app avec un profil permissif
      // pour pouvoir prévisualiser/auditer toutes les pages. En PROD on reste null (= restrictif/sûr).
      const isLocal = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
      permissions.value = isLocal ? { email, is_superuser: true, capabilities: {}, groups: ['admin'] } : null
    })
    .finally(() => {
      loading.value = false
      fetchPromise = null
    })

  return fetchPromise
}

/**
 * Check if the current user has a specific capability.
 * Superusers always return true.
 * Returns false if permissions haven't loaded yet (safe default).
 */
function can (capability) {
  if (!permissions.value) return false
  if (permissions.value.is_superuser) return true
  return permissions.value.capabilities?.[capability] === true
}

/**
 * Check if the user has ANY of the listed capabilities.
 */
function canAny (...capabilities) {
  return capabilities.some(c => can(c))
}

/**
 * Check if the user belongs to a specific group.
 */
function hasGroup (groupName) {
  return permissions.value?.groups?.includes(groupName) || false
}

// Computed helpers
const userGroups = computed(() => permissions.value?.groups || [])
const userName = computed(() => permissions.value?.name || '')
const userEmail = computed(() => permissions.value?.email || '')
const isSuperuser = computed(() => permissions.value?.is_superuser || false)
const isAdmin = computed(() => hasGroup('admin') || isSuperuser.value)
const isLoaded = computed(() => permissions.value !== null)

export function usePermissions () {
  return {
    permissions,
    loading,
    error,
    loadPermissions,
    can,
    canAny,
    hasGroup,
    userGroups,
    userName,
    userEmail,
    isSuperuser,
    isAdmin,
    isLoaded,
    HUB_URL,
  }
}
