import Taro from '@tarojs/taro'
import { clearStorageByLoginUser } from '@/utils/server'

/**
 * 登录态 / 游客态 标识。
 * - member: 已登录
 * - guest : 游客（未登录或登录态过期）
 */
export type UserMode = 'member' | 'guest'

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

export function getUserMode(): UserMode {
  return isLoggedIn() ? 'member' : 'guest'
}

export function isGuest(): boolean {
  return !isLoggedIn()
}

export function goToRegister(options?: { redirect?: string }) {
  const redirect = options?.redirect ? `?redirect=${encodeURIComponent(options.redirect)}` : ''
  Taro.navigateTo({ url: `/passport/login${redirect}` })
}

export function ensureLoggedIn(redirect?: string): boolean {
  if (isLoggedIn()) return true
  goToRegister({ redirect })
  return false
}

export function logout() {
  clearStorageByLoginUser()
}
