import { redirect } from '@tanstack/react-router'
import { useAuthStore } from '@/stores/auth-store'

export type PermissionMap = Record<string, string[]>

export type PermissionRequirement = {
  resource: string
  action?: string
}

export function hasPermission(
  permissions: PermissionMap | null | undefined,
  resource: string,
  action = 'read'
) {
  if (!permissions) {
    return false
  }

  if (permissions['*']?.includes('*')) {
    return true
  }

  const actions = permissions[resource] ?? permissions['*'] ?? []
  return actions.includes('*') || actions.includes(action)
}

export function canAccess(
  permissions: PermissionMap | null | undefined,
  requirement?: PermissionRequirement
) {
  if (!requirement) {
    return true
  }

  return hasPermission(
    permissions,
    requirement.resource,
    requirement.action ?? 'read'
  )
}

export function requirePermission(
  resource: string,
  action = 'read',
  redirectTo = '/403'
) {
  const permissions = useAuthStore.getState().auth.user?.permissions

  if (!hasPermission(permissions, resource, action)) {
    throw redirect({ to: redirectTo })
  }
}
