// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default defineNuxtPlugin(async (nuxtApp: any) => {
  // Helper function to safely fetch session, catching errors in test environment
  const safeFetchSession = async () => {
    try {
      await useAuth().fetchSession()
    } catch (error) {
      // In test environment, the /api/user/session endpoint doesn't exist
      // Silently catch and ignore these errors as tests should mock session state
      // In production, this would be a real error that should be logged
      if (import.meta.dev) {
        // Only log in development, not in tests
        const errorMessage = error instanceof Error ? error.message : String(error)
        if (!errorMessage.includes('Cannot find any path matching /api/user/session')) {
          console.error('[Auth Plugin] Error fetching session:', error)
        }
      }
    }
  }

  if (!nuxtApp.payload.serverRendered) {
    await safeFetchSession()
  } else if (Boolean(nuxtApp.payload.prerenderedAt) || Boolean(nuxtApp.payload.isCached)) {
    // To avoid hydration mismatch
    nuxtApp.hook('app:mounted', async () => {
      await safeFetchSession()
    })
  }
})
