/**
 * 用户状态管理
 */
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/api'
import type { User } from '@/types'

export const useUserStore = defineStore('user', () => {
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))

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

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

  // 登录
  const login = async (username: string, password: string) => {
    const formData = new FormData()
    formData.append('username', username)
    formData.append('password', password)
    
    const response = await api.post('/api/v1/auth/login', formData, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
    
    if (response.data.access_token) {
      setToken(response.data.access_token)
      await fetchUser()
    }
    
    return response.data
  }

  // 注册
  const register = async (username: string, email: string, password: string) => {
    const response = await api.post('/api/v1/auth/register', {
      username,
      email,
      password
    })
    
    return response.data
  }

  // 获取当前用户信息
  const fetchUser = async () => {
    if (!token.value) {
      throw new Error('未登录')
    }
    
    try {
      const response = await api.get('/api/v1/auth/me')
      user.value = response.data
      return response.data
    } catch (error: any) {
      // 如果401错误，清除token
      if (error.response?.status === 401) {
        clearToken()
      }
      throw error
    }
  }

  // 登出
  const logout = () => {
    user.value = null
    clearToken()
  }

  // 初始化：如果有token，设置axios header
  if (token.value) {
    api.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
  }

  return {
    user,
    token,
    login,
    register,
    logout,
    fetchUser
  }
})
