import type { UserRole } from '@skillmate/shared'
import { useAuthStore } from '../stores/authStore'

// Define role permissions directly to avoid import issues
const ROLE_PERMISSIONS: Record<UserRole, string[]> = {
  admin: [
    'admin:panel:access',
    'users:create',
    'users:read',
    'users:update', 
    'users:delete',
    'users:manage_roles',
    'employees:create',
    'employees:read',
    'employees:update',
    'employees:delete',
    'profiles:create',
    'profiles:read',
    'profiles:update',
    'profiles:delete'
  ],
  superuser: [
    'employees:create',
    'employees:read',
    'profiles:create',
    'profiles:read',
    'profiles:update_own'
  ],
  user: [
    'employees:read',
    'profiles:read',
    'profiles:update_own'
  ]
}

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

  const hasPermission = (permission: string): boolean => {
    if (!isAuthenticated || !user) return false
    
    const rolePermissions = ROLE_PERMISSIONS[user.role] || []
    return rolePermissions.includes(permission)
  }

  const hasRole = (role: string | string[]): boolean => {
    if (!isAuthenticated || !user) return false
    
    const allowedRoles = Array.isArray(role) ? role : [role]
    return allowedRoles.includes(user.role)
  }

  const canCreateEmployee = (): boolean => {
    return hasPermission('employees:create')
  }

  const canEditEmployee = (employeeId?: string): boolean => {
    if (!isAuthenticated || !user) return false
    
    // Admins can edit anyone
    if (user.role === 'admin') return true
    
    // Superusers can edit anyone
    if (user.role === 'superuser') return true
    
    // Users can only edit their own profile (if linked)
    if (user.role === 'user' && employeeId && user.employeeId === employeeId) {
      return true
    }
    
    return false
  }

  const canDeleteEmployee = (): boolean => {
    return hasPermission('employees:delete')
  }

  const canAccessAdminPanel = (): boolean => {
    return hasPermission('admin:panel:access')
  }

  const canManageUsers = (): boolean => {
    return hasPermission('users:create') || hasPermission('users:update') || hasPermission('users:delete')
  }

  return {
    hasPermission,
    hasRole,
    canCreateEmployee,
    canEditEmployee,
    canDeleteEmployee,
    canAccessAdminPanel,
    canManageUsers,
    user,
    isAuthenticated
  }
}
