// src/router/Guards.jsx
import React from 'react'
import { Navigate, Outlet, useLocation, useParams } from 'react-router-dom'
import { getUserInfo } from '../utils/auth'

/** 需登录 */
export function RequireAuth() {
  const user = getUserInfo()
  const location = useLocation()
  if (!user) {
    return <Navigate to="/login" state={{ from: location }} replace />
  }
  return <Outlet />
}

/** 需特定角色 */
export function RequireRole({ allowedRoles }) {
  const user = getUserInfo()
  if (!user || !allowedRoles.includes(user.role)) {
    return <Navigate to="/login" replace />
  }
  return <Outlet />
}

/** 只能访问自己的用户详情 */
export function RequireOwnProfile() {
  const user = getUserInfo()
  const { userId } = useParams()
  if (!user || user.id.toString() !== userId) {
    return <Navigate to="/home" replace />
  }
  return <Outlet />
}

/** 只能访问自己的 Admin 页面 */
export function RequireAdminOwn() {
  const user = getUserInfo()
  const { userId } = useParams()
  if (!user || user.role !== 'admin' || user.id.toString() !== userId) {
    return <Navigate to="/login" replace />
  }
  return <Outlet />
}

/** 只能访问自己的 SuperAdmin 区 */
export function RequireSuperAdminOwn() {
  const user = getUserInfo()
  const { userId } = useParams()
  if (!user || user.role !== 'superadmin' || user.id.toString() !== userId) {
    return <Navigate to="/login" replace />
  }
  return <Outlet />
}
