import { Navigate, Outlet } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import type { UserRole } from '../types';

interface RoleGuardProps {
  allowedRoles: UserRole[];
}

const ROLE_HOME: Record<string, string> = {
  purchaser: '/purchaser',
  textile: '/textile',
  washing: '/washing',
};

/**
 * 路由守卫：校验当前用户角色是否在允许列表中
 * - 未登录 → 重定向 /login
 * - 角色不匹配 → 重定向到当前角色的首页
 * - 角色匹配 → 渲染子路由
 */
export function RoleGuard({ allowedRoles }: RoleGuardProps) {
  const { auth, loading } = useAuth();

  if (loading) {
    return null;
  }

  if (!auth.isLoggedIn || !auth.user) {
    return <Navigate to="/login" replace />;
  }

  const currentRole = auth.currentRole;
  if (!currentRole || !allowedRoles.includes(currentRole)) {
    const redirectPath = currentRole ? ROLE_HOME[currentRole] : '/role-select';
    return <Navigate to={redirectPath || '/role-select'} replace />;
  }

  return <Outlet />;
}
