/** Wraps $fetch to redirect to /login on 401 for same-origin requests. */
export default defineNuxtPlugin(() => {
  const route = useRoute()
  const baseFetch = globalThis.$fetch ?? $fetch
  globalThis.$fetch = baseFetch.create({
    onResponseError({ response, request }) {
      if (response?.status !== 401) return
      const url = typeof request === 'string' ? request : request?.url ?? ''
      if (!url.startsWith('/')) return
      navigateTo({ path: '/login', query: { redirect: route.fullPath || '/' } }, { replace: true })
    },
  })
})
