export default defineNuxtRouteMiddleware(async (to, from) => {
  // Check if route requires auth
  const protectedRoutes = ['/mitgliederbereich', '/cms']
  const requiresAuth = protectedRoutes.some(route => to.path.startsWith(route))

  if (!requiresAuth) {
    return
  }

  // Check auth status
  try {
    const { data: auth } = await useFetch('/api/auth/status')
    
    if (!auth.value || !auth.value.isLoggedIn) {
      return navigateTo('/login?redirect=' + to.path)
    }

    // Check role for CMS
    if (to.path.startsWith('/cms')) {
      const isAdmin = auth.value.role === 'admin' || auth.value.role === 'vorstand'
      if (!isAdmin) {
        return navigateTo('/mitgliederbereich')
      }
    }
  } catch (error) {
    return navigateTo('/login?redirect=' + to.path)
  }
})

