import Cookies from "js-cookie";
import { useLocation } from "react-router-dom";
import { useAuth } from "@/shared/context/AuthContext";
import { useUser } from "@/shared/context/UserContext";

export function useExternalPortalSession() {
  const { user: authUser } = useAuth();
  const userDetails = useUser();
  const location = useLocation();

  const hasAuthToken = Boolean(Cookies.get("auth-token"));
  const resolvedUser = userDetails ?? authUser;
  const userType = resolvedUser?.userType;
  const isExternalPortalUser =
    userType === "external_organization" || userType === "individual";
  const isAuthenticated = Boolean(resolvedUser || hasAuthToken);
  const isOnExternalPortalRoute = location.pathname.startsWith(
    "/external-portal",
  );

  const showExternalPortalChrome =
    isAuthenticated && (isExternalPortalUser || isOnExternalPortalRoute);

  return {
    isAuthenticated,
    isExternalPortalUser,
    showExternalPortalChrome,
    resolvedUser,
    hasAuthToken,
  };
}
