import Taro, { useDidShow } from "@tarojs/taro";
import { getToken } from "../utils/auth";
import { currentPageUrl } from "../utils/onboarding";
import { ensureMemberAccess } from "../utils/permission";

export function useMemberGuard(message = "需成为会员后才能使用该功能") {
  useDidShow(() => {
    void (async () => {
      if (!getToken()) {
        const redirect = currentPageUrl();
        Taro.showToast({ title: "请先登录", icon: "none" });
        setTimeout(() => Taro.reLaunch({ url: redirect ? `/pages/login/index?redirect=${encodeURIComponent(redirect)}` : "/pages/login/index" }), 500);
        return;
      }
      await ensureMemberAccess(message);
    })();
  });
}
