import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  validateCredentials,
  getDefaultAdminUser,
  getTokenConfig,
  getAuthTimeouts
} from '@/config/auth'

export const useAuthStore = defineStore('auth', () => {
  // 获取配置
  const tokenConfig = getTokenConfig()
  const timeouts = getAuthTimeouts()

  // 状态
  const user = ref(null)
  const token = ref(localStorage.getItem(tokenConfig.tokenKey) || null)
  const isLoading = ref(false)
  const loginError = ref('')

  // 计算属性
  const isAuthenticated = computed(() => {
    return !!token.value && !!user.value
  })

  // 登录方法
  const login = async (credentials) => {
    isLoading.value = true
    loginError.value = ''

    try {
      // 模拟API调用 - 后续接入真实API
      await new Promise(resolve => setTimeout(resolve, timeouts.login))

      // 使用配置文件验证凭据
      if (validateCredentials(credentials.username, credentials.password)) {
        const mockUser = {
          ...getDefaultAdminUser(),
          username: credentials.username
        }

        const mockToken = tokenConfig.tokenPrefix + Date.now()

        // 更新状态
        user.value = mockUser
        token.value = mockToken

        // 保存到本地存储
        localStorage.setItem(tokenConfig.tokenKey, mockToken)
        localStorage.setItem(tokenConfig.userKey, JSON.stringify(mockUser))

        return { success: true, user: mockUser }
      } else {
        throw new Error('用户名或密码错误')
      }
    } catch (error) {
      loginError.value = error.message || '登录失败，请重试'
      return { success: false, error: error.message }
    } finally {
      isLoading.value = false
    }
  }

  // 登出方法
  const logout = () => {
    user.value = null
    token.value = null
    loginError.value = ''

    // 清除本地存储
    localStorage.removeItem(tokenConfig.tokenKey)
    localStorage.removeItem(tokenConfig.userKey)
  }

  // 初始化用户信息（从本地存储恢复）
  const initAuth = () => {
    const savedToken = localStorage.getItem(tokenConfig.tokenKey)
    const savedUser = localStorage.getItem(tokenConfig.userKey)

    if (savedToken && savedUser) {
      try {
        token.value = savedToken
        user.value = JSON.parse(savedUser)
      } catch {
        // 恢复失败时直接登出，不输出调试信息
        logout()
      }
    }
  }

  // 清除错误信息
  const clearError = () => {
    loginError.value = ''
  }

  // 检查token有效性（后续可扩展）
  const validateToken = async () => {
    if (!token.value) return false

    try {
      // 后续添加token验证API调用
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 0))
      return true
    } catch {
      logout()
      return false
    }
  }

  return {
    // 状态
    user,
    token,
    isLoading,
    loginError,

    // 计算属性
    isAuthenticated,

    // 方法
    login,
    logout,
    initAuth,
    clearError,
    validateToken
  }
})