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

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.user) {
        // 清除旧的权限数据
        const permissionStore = usePermissionStore()
        permissionStore.clearPermissions()
        
        user.value = response.user
        isAuthenticated.value = true
        
        // 保存登录状态到localStorage
        localStorage.setItem('jingrow_user', JSON.stringify(response.user))
        localStorage.setItem('jingrow_authenticated', 'true')
        
        // 加载新用户的权限
        await permissionStore.loadPermissions(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 permissionStore = usePermissionStore()
      permissionStore.clearPermissions()
    }
  }

  const initAuth = async () => {
    // 检查user_id是否为Guest（cookie过期时后端会设置为Guest）
    const cookies = new URLSearchParams(document.cookie.split('; ').join('&'))
    const userId = cookies.get('user_id')
    if (userId === 'Guest') {
      // user_id是Guest，说明cookie已过期，清除本地状态
      if (isAuthenticated.value) {
        await logout()
      }
      return
    }

    // 首先检查session cookie是否存在
    if (!isCookieExpired()) {
      try {
        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: any) {
        console.error('验证用户信息失败:', error)
        if (error.status === 401 || error.status === 403 || error.message?.includes('过期')) {
          await logout()
        }
        return
      }
    }

    // session cookie不存在，检查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
        localStorage.setItem('jingrow_user', JSON.stringify(userInfo))
      } catch (error: any) {
        console.error('验证用户信息失败:', error)
        if (error.status === 401 || error.status === 403 || error.message?.includes('过期')) {
          await logout()
        } else {
          logout()
        }
      }
    } else {
      if (isAuthenticated.value) {
        await 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: any) {
      console.error('更新用户信息失败:', error)
      // 如果是401/403错误，说明cookie已过期
      if (error.status === 401 || error.status === 403 || error.message?.includes('过期')) {
        await logout()
      }
    }
  }

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