import { useAuthStore } from '../stores/authStore.js'
import router from '../router/index.js'

let pendingAction = null

export function useAuthGate() {
  const authStore = useAuthStore()

  async function requireAuth({ message, onAuthenticated, redirectTo }) {
    if (authStore.isLoggedIn) {
      onAuthenticated?.()
    } else {
      pendingAction = onAuthenticated || null
      if (redirectTo) {
        router.push(redirectTo)
      } else if (message) {
        const { useUiStore } = await import('../stores/uiStore.js')
        const uiStore = useUiStore()
        uiStore.showToast(message, 'info')
      }
    }
  }

  function executePending() {
    if (pendingAction) {
      const fn = pendingAction
      pendingAction = null
      fn()
    }
  }

  return { requireAuth, executePending }
}
