import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'

interface User {
  id: string
  username: string
  email: string
  phone?: string
  avatar_url?: string
  is_active: boolean
}

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('access_token'))
  const loading = ref(false)

  const isAuthenticated = computed(() => !!token.value && !!user.value)

  // 设置token
  const setToken = (newToken: string) => {
    token.value = newToken
    localStorage.setItem('access_token', newToken)
    
    // 设置axios默认header
    axios.defaults.headers.common['Authorization'] = `Bearer ${newToken}`
  }

  // 清除token
  const clearToken = () => {
    token.value = null
    user.value = null
    localStorage.removeItem('access_token')
    delete axios.defaults.headers.common['Authorization']
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    if (!token.value) return
    
    try {
      const response = await axios.get('/api/user/profile')
      if (response.data.code === 0) {
        user.value = response.data.data
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      clearToken()
      throw error
    }
  }

  // 检查认证状态
  const checkAuth = async () => {
    if (token.value && !user.value) {
      try {
        await fetchUserInfo()
      } catch (error) {
        clearToken()
      }
    }
    
    // 设置axios默认header
    if (token.value) {
      axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
    }
  }

  // 登出
  const logout = async () => {
    try {
      if (token.value) {
        await axios.get('/auth/logout')
      }
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      clearToken()
    }
  }

  return {
    user,
    token,
    loading,
    isAuthenticated,
    setToken,
    clearToken,
    fetchUserInfo,
    checkAuth,
    logout
  }
})