/**
 * PWA Session Resume Plugin
 *
 * When the app returns from background (Android kills PWA processes after ~1 hour),
 * this plugin proactively refreshes the auth token before any API call can fail.
 *
 * Only active for PWA standalone mode — desktop browser tabs are not affected.
 */
export default defineNuxtPlugin(() => {
  const isPwa = window.matchMedia('(display-mode: standalone)').matches || !!navigator['standalone']
  if (!isPwa) return

  let refreshing = false

  const refreshSession = async () => {
    if (refreshing) return

    // Only refresh if user was logged in (has user cookie)
    const user = useCookie('logship_user')
    if (!user.value?.id) return

    refreshing = true

    try {
      // Validate token against iDempiere and refresh if expired
      const res = await $fetch('/api/idempiere-auth/session-refresh', {
        method: 'POST',
        headers: useRequestHeaders(['cookie'])
      })

      if (!res?.valid) {
        // Token refresh also failed — redirect to signin
        // Auto-login will kick in if credentials are stored
        navigateTo('/signin')
      }
    } catch {
      // Network error or server down — don't logout, just let the user retry naturally
    } finally {
      refreshing = false
    }
  }

  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'visible') {
      refreshSession()
    }
  })
})