import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/api'

let unauthorizedListenerRegistered = false

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(localStorage.getItem('access_token'))
  const user = ref<{ id: string; username: string; email: string; full_name?: string } | null>(null)
  const isAuthReady = ref(false)
  const isFetchingUser = ref(false)
  let authReadyPromise: Promise<void> | null = null

  const isAuthenticated = computed(() => !!token.value)

  async function login(identifier: string, password: string) {
    const formData = new FormData()
    formData.append('username', identifier)
    formData.append('password', password)
    const response = await api.post('/api/auth/login', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    token.value = response.data.access_token
    localStorage.setItem('access_token', response.data.access_token)
    user.value = null
    isAuthReady.value = false
    await fetchUser()
  }

  async function fetchUser() {
    if (!token.value) {
      user.value = null
      isAuthReady.value = true
      return
    }

    isFetchingUser.value = true
    try {
      const response = await api.get('/api/auth/me')
      user.value = response.data
    } catch (error: any) {
      const status = error?.response?.status
      if (status === 401 || status === 403) {
        logout()
      } else {
        console.error('获取当前用户失败:', error)
      }
    } finally {
      isFetchingUser.value = false
      isAuthReady.value = true
    }
  }

  function logout() {
    token.value = null
    user.value = null
    isFetchingUser.value = false
    isAuthReady.value = true
    localStorage.removeItem('access_token')
  }

  async function ensureAuthReady() {
    if (isAuthReady.value) return
    if (!authReadyPromise) {
      authReadyPromise = fetchUser().finally(() => {
        authReadyPromise = null
      })
    }
    await authReadyPromise
  }

  if (typeof window !== 'undefined' && !unauthorizedListenerRegistered) {
    window.addEventListener('jarvis:auth-unauthorized', logout)
    unauthorizedListenerRegistered = true
  }

  if (token.value) {
    void ensureAuthReady()
  } else {
    isAuthReady.value = true
  }

  return { token, user, isAuthenticated, isAuthReady, isFetchingUser, login, logout, fetchUser, ensureAuthReady }
})
