import { useContext } from "react";
import { Navigate } from "react-router-dom";
import { AuthContext } from "@/contexts/AuthContext";

// Define available pages in order of priority
const PAGES = [
  { path: "/products", permission: "access:products" },
  { path: "/categories", permission: "access:categories" },
  { path: "/vendors", permission: "access:vendors" },
  { path: "/purchase-orders", permission: "access:purchase_orders" },
  { path: "/analytics", permission: "access:analytics" },
  { path: "/forecasting", permission: "access:forecasting" },
  { path: "/import", permission: "access:import" },
  { path: "/settings", permission: "access:settings" },
  { path: "/ai-validation/debug", permission: "access:ai_validation_debug" }
];

export function FirstAccessiblePage() {
  const { user } = useContext(AuthContext);
  
  // If user isn't loaded yet, don't render anything
  if (!user) {
    return null;
  }
  
  // Admin users have access to all pages, so this component 
  // shouldn't be rendering for them (handled by App.tsx)
  if (user.is_admin) {
    return null;
  }
  
  // Find the first page the user has access to
  const firstAccessiblePage = PAGES.find(page => {
    return user.permissions?.includes(page.permission);
  });
  
  // If we found a page, redirect to it
  if (firstAccessiblePage) {
    return <Navigate to={firstAccessiblePage.path} replace />;
  }
  
  // If user has no access to any page, redirect to login
  return <Navigate to="/login" replace />;
}
