// 认证状态管理
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { apiClient } from '@/api/client'
import { createLogger } from '@/utils/logger'

const logger = createLogger('AuthStore')

export interface User {
  id: number
  username: string
  email: string
  role: string
  permissions: string[]
}

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const loading = ref(false)
  
  // 计算属性
  const isAuthenticated = computed(() => !!token.value && !!user.value)
  const isAdmin = computed(() => user.value?.role === 'admin')
  const hasPermission = computed(() => (permission: string) => {
    return user.value?.permissions?.includes(permission) ?? false
  })
  
  // 方法
  const login = async (username: string, password: string) => {
    loading.value = true
    logger.info('尝试登录', { username })
    
    try {
      const response = await apiClient.post('/auth/login', { username, password })
      
      // 保存token和用户信息
      token.value = response.token
      user.value = response.user
      
      // 保存到localStorage
      localStorage.setItem('auth_token', response.token)
      localStorage.setItem('user_info', JSON.stringify(response.user))
      
      logger.info('登录成功', { user: response.user.username })
      return response
    } catch (error) {
      logger.error('登录失败', error)
      throw error
    } finally {
      loading.value = false
    }
  }
  
  const logout = () => {
    logger.info('用户登出')
    user.value = null
    token.value = null
    localStorage.removeItem('auth_token')
    localStorage.removeItem('user_info')
  }
  
  const refreshUser = async () => {
    if (!token.value) return
    
    try {
      const userData = await apiClient.get('/auth/me')
      user.value = userData
      localStorage.setItem('user_info', JSON.stringify(userData))
      logger.info('用户信息已刷新')
    } catch (error) {
      logger.error('刷新用户信息失败', error)
    }
  }
  
  const initialize = () => {
    // 从localStorage恢复状态
    const savedToken = localStorage.getItem('auth_token')
    const savedUser = localStorage.getItem('user_info')
    
    if (savedToken) {
      token.value = savedToken
      logger.info('从本地存储恢复 token')
    }
    
    if (savedUser) {
      try {
        user.value = JSON.parse(savedUser)
        logger.info('从本地存储恢复用户信息')
      } catch (error) {
        logger.error('解析用户信息失败', error)
        localStorage.removeItem('user_info')
      }
    }
    
    // 如果有token但没有用户信息，尝试刷新
    if (token.value && !user.value) {
      refreshUser()
    }
  }
  
  // 初始化
  initialize()
  
  return {
    // 状态
    user,
    token,
    loading,
    
    // 计算属性
    isAuthenticated,
    isAdmin,
    hasPermission,
    
    // 方法
    login,
    logout,
    refreshUser,
  }
})
