export default defineNuxtRouteMiddleware(async (to, _from) => {
  // Check if route requires authentication
  const mw = to.meta.middleware
  const requiresAuth =
    mw === 'auth' || (Array.isArray(mw) && mw.includes('auth'))

  if (requiresAuth) {
    // Nicht auf Pinia angewiesen sein (sonst "no active Pinia" in manchen Nuxt-Lifecycle-Phasen)
    try {
      const { data: auth } = await useFetch('/api/auth/status')
      if (!auth.value || !auth.value.isLoggedIn) {
        const redirect = encodeURIComponent(to.fullPath || to.path || '/')
        return navigateTo(`/login?redirect=${redirect}`)
      }
    } catch (_e) {
      const redirect = encodeURIComponent(to.fullPath || to.path || '/')
      return navigateTo(`/login?redirect=${redirect}`)
    }
  }
})

