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

// Define available pages in order of priority
// Dashboard is first so users with dashboard access default to it
const PAGES = [
  { path: "/dashboard", permission: "access:dashboard" },
  { path: "/dashboard/black-friday", permission: "access:black_friday_dashboard" },
  { path: "/overview", permission: "access:overview" },
  { path: "/products", permission: "access:products" },
  { path: "/categories", permission: "access:categories" },
  { path: "/brands", permission: "access:brands" },
  { path: "/purchase-orders", permission: "access:purchase_orders" },
  { path: "/analytics", permission: "access:analytics" },
  { path: "/discount-simulator", permission: "access:discount_simulator" },
  { path: "/hts-lookup", permission: "access:hts_lookup" },
  { path: "/spec-lookup", permission: "access:spec_lookup" },
  { 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;
  }
  
  // Admins can access every page, otherwise check explicit permissions
  const firstAccessiblePage = PAGES.find(page => {
    if (user.is_admin) {
      return true;
    }

    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 />;
}
