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

export interface User {
  id: string
  name: string
  username: string
  email: string
  avatar?: string
  first_name?: string
  last_name?: string
  user_type?: string
  recent?: string  // JSON string of recent pages
  can_read?: string[]  // PageTypes user can read
  can_create?: string[]  // PageTypes user can create
  can_search?: string[]  // PageTypes user can search
}

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const loading = ref(false)
  const isAuthenticated = ref(false)
  const workspaces = ref<Array<{ name: string; label: string }>>([])
  const initPromise = ref<Promise<void> | null>(null)

  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
        
        // Initialize slug mapping from user's can_read list
        if (response.user.can_read?.length) {
          initSlugMapping(response.user.can_read)
        }
        
        // 保存登录状态到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()
      
      // 清除服务端注入的 boot 数据
      if (typeof window !== 'undefined' && (window as any).jingrow?.boot) {
        (window as any).jingrow.boot.user = { name: 'Guest' }
      }
      
      initPromise.value = null
    }
  }

  const initAuth = async () => {
    if (initPromise.value) return initPromise.value
    
    initPromise.value = (async () => {
      if (typeof window !== 'undefined') {
        if (!(window as any).jingrow) (window as any).jingrow = {}
        if (!(window as any).jingrow.boot) (window as any).jingrow.boot = {}
      }
      
      const cookies = new URLSearchParams(document.cookie.split('; ').join('&'))
      const userId = cookies.get('user_id')
      
      if (userId === 'Guest' || !userId) return

      let bootUser = (window as any).jingrow?.boot?.user
      
      if (!bootUser || bootUser.name === 'Guest') {
        try {
          const response = await fetch('/api/action/jingrow.sessions.get_boot_info', {
            method: 'GET',
            headers: { 'Accept': 'application/json' },
            credentials: 'include'
          })
          if (response.ok) {
            const result = await response.json()
            ;(window as any).jingrow.boot = result.message
            bootUser = result.message.user
          }
        } catch (e) {
          // Failed to fetch boot info
        }
      }

      if (bootUser && bootUser.name !== 'Guest') {
        user.value = {
          id: bootUser.name || bootUser.user || '',
          name: bootUser.name || bootUser.user || '',
          username: bootUser.name || bootUser.user || '',
          email: bootUser.email || '',
          avatar: bootUser.user_image || '',
          first_name: bootUser.first_name || '',
          last_name: bootUser.last_name || '',
          user_type: bootUser.user_type || 'System User',
          recent: bootUser.recent || '[]',
          can_read: bootUser.can_read || [],
          can_create: bootUser.can_create || [],
          can_search: bootUser.can_search || []
        }
        isAuthenticated.value = true
        
        if (bootUser.can_read?.length) {
          initSlugMapping(bootUser.can_read)
        }
        
        localStorage.setItem('jingrow_user', JSON.stringify(user.value))
        localStorage.setItem('jingrow_authenticated', 'true')
      }
      
      if ((window as any).jingrow?.boot?.setup_complete === undefined) {
        try {
          const response = await fetch('/api/data/System%20Settings/System%20Settings?fields=["setup_complete"]')
          if (response.ok) {
            const data = await response.json()
            ;(window as any).jingrow.boot.setup_complete = data?.data?.setup_complete
          }
        } catch (e) {
          // API call failed
        }
      }
    })()
    
    return initPromise.value
  }

  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,
    workspaces,
    login,
    logout,
    initAuth,
    updateUserInfo
  }
})
