/**
 * Centralized permissions hook for ResolutionFlow.
 *
 * Role hierarchy: super_admin > owner > engineer > viewer
 *
 * Mirrors backend logic in backend/app/core/permissions.py
 */
import { useAuthStore } from '@/store/authStore'
import type { User } from '@/types'

export type EffectiveRole = 'super_admin' | 'owner' | 'engineer' | 'viewer'

const ROLE_HIERARCHY: Record<EffectiveRole, number> = {
  super_admin: 4,
  owner: 3,
  engineer: 2,
  viewer: 1,
}

function getEffectiveRole(user: User | null): EffectiveRole {
  if (!user) return 'viewer'
  if (user.is_super_admin) return 'super_admin'
  if (user.account_role === 'owner') return 'owner'
  return user.role as EffectiveRole
}

function hasMinimumRole(user: User | null, minimum: EffectiveRole): boolean {
  const effective = getEffectiveRole(user)
  return ROLE_HIERARCHY[effective] >= ROLE_HIERARCHY[minimum]
}

export function usePermissions() {
  const { user } = useAuthStore()

  const effectiveRole = getEffectiveRole(user)

  return {
    effectiveRole,
    isSuperAdmin: effectiveRole === 'super_admin',
    isAccountOwner: effectiveRole === 'owner' || effectiveRole === 'super_admin',
    isEngineer: hasMinimumRole(user, 'engineer'),
    isViewer: effectiveRole === 'viewer',

    // Content creation permissions
    canCreateTrees: hasMinimumRole(user, 'engineer'),
    canCreateSteps: hasMinimumRole(user, 'engineer'),

    // Resource-specific checks
    canEditTree: (tree: { author_id: string | null; account_id?: string | null }) => {
      if (!user) return false
      if (user.is_super_admin) return true
      if (!hasMinimumRole(user, 'engineer')) return false
      if (tree.author_id && tree.author_id === user.id) return true
      if (user.account_role === 'owner' && tree.account_id === user.account_id && user.account_id) return true
      return false
    },

    canDeleteTree: () => {
      if (!user) return false
      return user.is_super_admin
    },

    canEditStep: (step: { created_by: string }) => {
      if (!user) return false
      if (user.is_super_admin) return true
      if (!hasMinimumRole(user, 'engineer')) return false
      return step.created_by === user.id
    },

    // Management permissions
    canManageCategories: hasMinimumRole(user, 'owner'),
    canManageGlobalCategories: effectiveRole === 'super_admin',
    canManageAccount: effectiveRole === 'super_admin' || effectiveRole === 'owner',
  }
}
