import Taro from '@tarojs/taro'
import { goTo } from '@/utils/navigation'
import { getStoredInviteParams } from '@/utils/invite'

export function isLoggedIn(): boolean {
  const token = Taro.getStorageSync('access_token')
  const userId = Taro.getStorageSync('UserId')
  return !!token && !!userId
}

export function goToRegister(options?: { redirect?: string }) {
  const inviteParams = getStoredInviteParams()
  goTo('/passport/register', {
    redirect: options?.redirect,
    inviter: inviteParams?.inviter,
    source: inviteParams?.source,
    t: inviteParams?.t,
  })
}

/**
 * Ensure user is logged in; if not, navigate to register/login page.
 * @returns true when already logged in; false when redirected to register
 */
export function ensureLoggedIn(redirect?: string): boolean {
  if (isLoggedIn()) return true
  goToRegister({ redirect })
  return false
}

