import { useEffect } from "react"; import { useNavigate } from "@remix-run/react"; import { useServiceGetProfile } from "../requestHandler/use-profile-hooks"; export function useStoreOwnership(storeId: string | undefined, mode?: string) { const navigate = useNavigate(); const { data: profileData, isLoading } = useServiceGetProfile(); useEffect(() => { // Wait for profile data to load if (isLoading) return; // If no storeId provided, redirect to home if (!storeId && mode !== "create") { navigate("/"); return; } // If user doesn't have profile data, redirect to home if (!profileData) { navigate("/"); return; } // If user doesn't have a seller account, redirect to home if (!profileData.sellerUsername && mode !== "create") { navigate("/"); return; } // If the storeId doesn't match the user's seller username, redirect to their own store if ( profileData.sellerUsername !== storeId && mode !== "create" && storeId ) { navigate(`/store/${profileData.sellerUsername}`); return; } }, [profileData, storeId, isLoading, navigate, mode]); return { isOwner: profileData?.sellerUsername === storeId, isLoading, userStoreId: profileData?.sellerUsername, }; }