/**
 * Auth Middleware
 *
 * Protects routes that require authentication.
 * Redirects to login if user is not authenticated.
 *
 * Works on both server and client:
 * - Server: Forwards cookies from incoming request to /api/auth/me
 * - Client: Browser sends cookies automatically
 */

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

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

  // If already authenticated (from previous navigation), allow access
  if (authStore.isAuthenticated) {
    console.log('[Auth Middleware] Already authenticated, allowing access to:', to.path)
    return
  }

  // Check auth status by calling backend
  console.log('[Auth Middleware] Checking auth for:', to.path)
  const isAuthed = await authStore.checkAuth()

  console.log('[Auth Middleware]', {
    path: to.path,
    isAuthenticated: isAuthed,
    hasUser: !!authStore.currentUser,
  })

  // Allow access if authenticated
  if (isAuthed) {
    return
  }

  // Redirect to login with return URL
  console.log('[Auth Middleware] Not authenticated, redirecting to login')
  return navigateTo({
    path: '/auth/login',
    query: { redirect: to.fullPath },
  })
})
