/** @format */

import { ref } from "vue"
import { defineStore } from "pinia"
import { loginApi, logoutApi } from "~/api/model/user"

interface LoginRequestData {
  email: string
  password: string
}

export const useUserStore = defineStore(
  "user",
  () => {
    const userInfo = shallowRef<any>()
    const token = shallowRef<any>()
    const isLogin = computed(() => !!token.value)
    const avatar = computed(() => userInfo.value?.avatar)
    const nickname = computed(() => userInfo.value?.email)
    /** 登录操作 */
    const login = async (params: LoginRequestData) => {
      try {
        const data: any = await loginApi(params)
        const { token: userToken, userInfo: userDataInfo } = data
        userInfo.value = userDataInfo
        token.value = userToken
        ElMessage({
          message: "Login success",
          type: "success",
          plain: true,
        })
      } catch (error) {
        return Promise.reject(error)
      }
    }
    /** 退出登录操作 */
    const logout = async () => {
      try {
        if (token.value) {
          await logoutApi()
          document.cookie =
            "user=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/"
          ElMessage({
            message: "Exit successful",
            type: "success",
            plain: true,
          })
        }
      } finally {
        token.value = null
        userInfo.value = undefined
        const router = useRouter()
        router.push("/")
      }
    }
    return { userInfo, token, login, logout, isLogin, avatar, nickname }
  },
  {
    persist: true,
  }
)
