/**
 * Auth Middleware
 *
 * Protects routes that require authentication.
 * Redirects to login if user is not authenticated.
 */

import { useAuthStore } from '~/store/auth'

export default defineNuxtRouteMiddleware((to, from) => {
  const authStore = useAuthStore()

  // Initialize auth from localStorage if not already done
  if (process.client && !authStore.isAuthenticated) {
    authStore.initializeAuth()
  }

  // Allow access if authenticated
  if (authStore.isAuthenticated) {
    return
  }

  // Redirect to login with return URL
  return navigateTo({
    path: '/auth/login',
    query: { redirect: to.fullPath },
  })
})
