import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { AdminInfo, LoginParams } from '@/types'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, logout, getInfo } from '@/api/login'

export const useUserStore = defineStore('user', () => {
  const token = ref<string>(getToken() || '')
  const userInfo = ref<AdminInfo | null>(null)

  async function loginAction(loginForm: LoginParams) {
    const res = await login(loginForm)
    if (res.success && res.data) {
      const { token: accessToken, expiresIn, admin } = res.data
      token.value = accessToken
      // 使用 cookie 存储 token，设置过期时间
      setToken(accessToken, expiresIn)
      // 设置用户信息
      if (admin) {
        userInfo.value = admin
      }
    }
    return res
  }

  async function getUserInfo() {
    const res = await getInfo()
    if (res.success && res.data) {
      userInfo.value = res.data
    }
    return res
  }

  async function logoutAction() {
    try {
      await logout()
    } catch (error) {
      // 忽略登出 API 错误，无论成功失败都要清空本地数据
      console.warn('Logout API failed:', error)
    } finally {
      token.value = ''
      userInfo.value = null
      removeToken()
    }
  }

  function resetToken() {
    token.value = ''
    userInfo.value = null
    removeToken()
  }

  return {
    token,
    userInfo,
    loginAction,
    getUserInfo,
    logoutAction,
    resetToken
  }
})
