import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { 
  login as loginApi, 
  getUserInfo as getUserInfoApi, 
  logout as logoutApi,
  revokeAllTokens as revokeAllTokensApi,
  type LoginRequest, 
  type UserInfo 
} from '@/api/auth'
import { 
  setTokens, 
  clearTokens, 
  getAccessToken, 
  getRefreshToken 
} from '@/utils/auth'
import router, { resetRouter } from '@/router'

export const useUserStore = defineStore('user', () => {
  const accessToken = ref<string | null>(getAccessToken())
  const refreshToken = ref<string | null>(getRefreshToken())
  const userInfo = ref<UserInfo | null>(null)

  // Computed property for legacy compatibility
  const token = computed(() => accessToken.value)

  // 登录
  async function login(loginForm: LoginRequest) {
    const res = await loginApi(loginForm)
    const { accessToken: newAccessToken, refreshToken: newRefreshToken, expiresIn, userInfo: newUserInfo } = res.data
    
    // Handle both new and legacy response formats
    const tokenToUse = newAccessToken || (res.data as any).token
    const refreshTokenToUse = newRefreshToken || ''
    
    accessToken.value = tokenToUse
    refreshToken.value = refreshTokenToUse
    userInfo.value = newUserInfo
    
    // Store tokens
    if (refreshTokenToUse) {
      setTokens(tokenToUse, refreshTokenToUse, expiresIn)
    } else {
      // Legacy mode - just store access token
      setTokens(tokenToUse, '', expiresIn)
    }
    
    return res
  }

  // 获取用户信息
  async function getUserInfo() {
    const res = await getUserInfoApi()
    userInfo.value = res.data
    return res.data
  }

  // 退出登录 - 撤销当前设备的 RefreshToken
  async function logout() {
    try {
      // 调用后端登出接口，撤销 RefreshToken
      await logoutApi()
    } catch (e) {
      // 忽略错误，即使后端调用失败也要清除本地状态
      console.warn('Logout API call failed:', e)
    }
    
    // 清除本地状态
    accessToken.value = null
    refreshToken.value = null
    userInfo.value = null
    clearTokens()
    resetRouter()
    router.push('/login')
  }

  // 强制登出所有设备 - 撤销用户所有 RefreshToken
  async function logoutAllDevices() {
    try {
      await revokeAllTokensApi()
    } catch (e) {
      console.warn('Revoke all tokens API call failed:', e)
    }
    
    // 清除本地状态
    accessToken.value = null
    refreshToken.value = null
    userInfo.value = null
    clearTokens()
    resetRouter()
    router.push('/login')
  }

  // 重置状态（不调用后端，仅清除本地状态）
  function resetState() {
    accessToken.value = null
    refreshToken.value = null
    userInfo.value = null
    clearTokens()
  }

  // 更新Token（用于Token刷新后更新store状态）
  function updateTokens(newAccessToken: string, newRefreshToken: string, expiresIn?: number) {
    accessToken.value = newAccessToken
    refreshToken.value = newRefreshToken
    
    // Also update storage if expiresIn is provided
    if (expiresIn !== undefined) {
      setTokens(newAccessToken, newRefreshToken, expiresIn)
    }
  }

  // 检查是否已登录
  function isLoggedIn(): boolean {
    return !!accessToken.value
  }

  return {
    token, // Legacy compatibility (computed)
    accessToken,
    refreshToken,
    userInfo,
    login,
    getUserInfo,
    logout,
    logoutAllDevices,
    resetState,
    updateTokens,
    isLoggedIn
  }
})
