import { computed } from 'vue'
import { useAuthStore } from '@/stores/auth'

/**
 * Shared role/admin checks for the dominant duplicated permission pattern
 * (`is_admin || role === 'coordinator'`) found across ~15 components.
 * Not a generic `can()` — a couple of call sites check genuinely different
 * things (ownership, a third "developer" role) and are left as-is.
 */
export function usePermission() {
  const authStore = useAuthStore()

  const isAdmin = computed(() => !!authStore.user?.is_admin)
  const isCoordinatorOrAdmin = computed(() =>
    authStore.user?.role === 'coordinator' || !!authStore.user?.is_admin
  )

  /**
   * Resource/action check backed by the new multi-role permission system
   * (e.g. hasPermission('shot', 'create')). Reads authStore.user.permissions,
   * which is only ever populated on the current session's own user.
   */
  function hasPermission(resource: string, action: string): boolean {
    if (authStore.isAdmin) return true
    return authStore.user?.permissions?.includes(`${resource}:${action}`) ?? false
  }

  return { isAdmin, isCoordinatorOrAdmin, hasPermission }
}
