export default defineNuxtRouteMiddleware(async (to, from) => {
  const guestPaths = ['/signin', '/select-role', '/login', '/register', '/verify-email', '/forgot-password', '/reset-password']

  if(!guestPaths.includes(from.path)) {
    const user = useCookie('logship_user')

    try {
      const authenticated = await $fetch('/api/idempiere-auth/authenticated', {
        headers: useRequestHeaders(['cookie'])
      })
      if(authenticated.user?.id === undefined || user.value?.id === undefined) {
        return navigateTo('/signin')
      }
    } catch (error: any) {
      // On mobile/PWA, don't logout on network errors - just check the cookie
      const isMobilePage = to.path.startsWith('/mobile')
      const isPwa = process.client && (window.matchMedia('(display-mode: standalone)').matches || !!navigator['standalone'])

      if (isMobilePage || isPwa) {
        // For mobile/PWA, only logout if user cookie is actually missing
        // Network errors should not trigger logout
        if (!user.value?.id) {
          console.warn('[Auth] Auth check failed, no user cookie:', error?.message)
          return navigateTo('/signin')
        }
        // User cookie exists, allow navigation despite API error
        console.warn('[Auth] Auth API error, but user cookie exists - continuing:', error?.message)
        return
      }

      // For desktop browser pages, redirect on any auth error
      console.error('[Auth] Authentication check failed:', error?.message)
      return navigateTo('/signin')
    }
  }
})
