/**
 * Auth Middleware
 *
 * Protects routes that require authentication.
 * Redirects to login if user is not authenticated.
 *
 * Note: Auth state is initialized by the auth.client.ts plugin before this middleware runs.
 */

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

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

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

  // Allow access if authenticated and token is valid
  if (authStore.isAuthenticated && authStore.isTokenValid) {
    return
  }

  // If token expired but we have a refresh token, try refreshing
  if (authStore.isAuthenticated && !authStore.isTokenValid && process.client) {
    console.log('[Auth Middleware] Token expired, attempting refresh')
    // Don't await - let it refresh in background and redirect for now
    authStore.refreshAccessToken()
  }

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