import { useAuth } from "@/contexts/AuthContext";
import { useNavigate } from "react-router-dom";
import { useToast } from "@/hooks/use-toast";
import { useCallback } from "react";

/**
 * 用于在执行需要登录的关键动作前进行守卫。
 * 未登录时会提示并跳转到 /auth，并返回 false。
 */
export function useRequireAuth() {
  const { user } = useAuth();
  const navigate = useNavigate();
  const { toast } = useToast();

  const requireAuth = useCallback(
    (action?: string): boolean => {
      if (user) return true;
      toast({
        title: "请先登录",
        description: action ? `登录后即可${action}` : "登录后即可继续操作",
      });
      navigate("/auth");
      return false;
    },
    [user, navigate, toast]
  );

  return { requireAuth, isAuthenticated: !!user };
}
