import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { loginApi, getUserInfoApi, logoutApi, getSessionUser } from '../api/auth'

export interface User {
  id: string
  username: string
  email: string
  avatar?: string
  first_name?: string
  last_name?: string
  user_type?: string
}

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const loading = ref(false)
  const isAuthenticated = ref(false)

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

  const login = async (username: string, password: string) => {
    loading.value = true
    try {
      const response = await loginApi(username, password)
      
      if (response.message === 'Logged In' && response.user) {
        user.value = response.user
        isAuthenticated.value = true
        
        // 保存登录状态到localStorage
        localStorage.setItem('jingrow_user', JSON.stringify(response.user))
        localStorage.setItem('jingrow_authenticated', 'true')
        
        return { success: true, user: response.user }
      } else {
        return { success: false, error: response.message || '登录失败' }
      }
    } catch (error: any) {
      console.error('登录错误:', error)
      return { success: false, error: error.message || '登录失败' }
    } finally {
      loading.value = false
    }
  }

  const logout = async () => {
    try {
      await logoutApi()
    } catch (error) {
      console.error('登出错误:', error)
    } finally {
      // 清除本地状态
      user.value = null
      isAuthenticated.value = false
      localStorage.removeItem('jingrow_user')
      localStorage.removeItem('jingrow_authenticated')
    }
  }

  const initAuth = async () => {
    // 首先检查Cookie中的session
    const sessionUser = getSessionUser()
    if (sessionUser) {
      try {
        // 从Cookie获取到用户，验证用户信息
        const userInfo = await getUserInfoApi()
        user.value = userInfo
        isAuthenticated.value = true
        
        // 更新localStorage
        localStorage.setItem('jingrow_user', JSON.stringify(userInfo))
        localStorage.setItem('jingrow_authenticated', 'true')
        return
      } catch (error) {
        console.error('验证用户信息失败:', error)
      }
    }

    // 如果Cookie中没有session，检查localStorage
    const savedUser = localStorage.getItem('jingrow_user')
    const savedAuth = localStorage.getItem('jingrow_authenticated')
    
    if (savedUser && savedAuth === 'true') {
      try {
        user.value = JSON.parse(savedUser)
        isAuthenticated.value = true
        
        // 验证用户信息是否仍然有效
        const userInfo = await getUserInfoApi()
        user.value = userInfo
      } catch (error) {
        console.error('验证用户信息失败:', error)
        logout()
      }
    }
  }

  const updateUserInfo = async () => {
    if (!isAuthenticated.value) return
    
    try {
      const userInfo = await getUserInfoApi()
      user.value = userInfo
      localStorage.setItem('jingrow_user', JSON.stringify(userInfo))
    } catch (error) {
      console.error('更新用户信息失败:', error)
    }
  }

  return {
    user,
    loading,
    isAuthenticated,
    isLoggedIn,
    login,
    logout,
    initAuth,
    updateUserInfo
  }
})
