import { redirect } from 'react-router'
import { useAuthStore } from '@/stores/useAuthStore'
import { usePermissionStore } from '@/stores/usePermissionStore'

export async function authLoader() {
  const token = localStorage.getItem('token')

  if (!token) {
    return redirect('/login')
  }

  let authState = useAuthStore.getState()

  if (!authState.initialized) {
    authState.initFromStorage()
    authState = useAuthStore.getState()
  }

  if (!authState.isAuthenticated) {
    return redirect('/login')
  }

  let permState = usePermissionStore.getState()

  if (!permState.loaded) {
    const restored = permState.initFromStorage()
    if (!restored) {
      try {
        await permState.fetchUserMenus()
      } catch {
        authState = useAuthStore.getState()
        authState.logout()
        return redirect('/login')
      }
    }
    permState = usePermissionStore.getState()
  }

  return null
}
