import Taro from '@tarojs/taro'
import type { TokenDTO, UserInfoDTO } from '@/api/types'

const tokenKey = 'simple-todo-app-token'
const userKey = 'simple-todo-app-user'

export function getToken() {
  return Taro.getStorageSync<string>(tokenKey) || ''
}

export function getCurrentUser() {
  return Taro.getStorageSync<UserInfoDTO>(userKey) || {}
}

export function isLoggedIn() {
  return Boolean(getToken())
}

export function setLoginSession(data: TokenDTO) {
  Taro.setStorageSync(tokenKey, data.token)
  Taro.setStorageSync(userKey, data.currentUser.userInfo)
}

export function setCurrentUser(user: UserInfoDTO) {
  Taro.setStorageSync(userKey, user)
}

export function clearLoginSession() {
  Taro.removeStorageSync(tokenKey)
  Taro.removeStorageSync(userKey)
}

export function redirectToLogin() {
  clearLoginSession()
  Taro.reLaunch({ url: '/pages/login/index' })
}

