import { Navigate, Outlet } from 'react-router-dom'
import { Result, Spin } from 'antd'
import { useAuth } from '@/stores/auth'

const RequireAuth = () => {
  const { user } = useAuth()
  if (!user) return <Navigate to="/login" replace />
  return <Outlet />
}

export const RequirePlatformAdmin = () => {
  const { user } = useAuth()
  if (!user) return <Navigate to="/login" replace />
  if (user.role !== 'platform_admin') return <Navigate to="/agent/dashboard" replace />
  return <Outlet />
}

export const RequireStaff = () => {
  const { user } = useAuth()
  if (!user) return <Navigate to="/login" replace />
  if (user.role === 'platform_admin') return <Navigate to="/admin/dashboard" replace />
  return <Outlet />
}

export const RequireSupervisor = () => {
  const { user } = useAuth()
  if (!user) return <Navigate to="/login" replace />
  if (user.role !== 'admin' && user.role !== 'supervisor') return <Navigate to="/agent/dashboard" replace />
  return <Outlet />
}

export const RequireTenantAdmin = () => {
  const { user } = useAuth()
  if (!user) return <Navigate to="/login" replace />
  if (user.role !== 'admin') return <Navigate to="/agent/dashboard" replace />
  return <Outlet />
}

export const RequirePermission = ({ anyOf }: { anyOf: string[] }) => {
  const { user, permissions, permissionsLoaded } = useAuth()
  if (!user) return <Navigate to="/login" replace />
  if (!permissionsLoaded) {
    return <div className="h-full flex items-center justify-center"><Spin /></div>
  }
  if (!anyOf.some(code => permissions.has(code))) {
	return <Result status="403" title="403" subTitle="无权访问此页面" />
  }
  return <Outlet />
}

export default RequireAuth
