import type { H3Event } from 'h3'
import type { AuthSession as ServerAuthSession } from '../../server/types/api'
import type { AuthSession, AuthUser } from '../types/auth'
import type { NuxtApp } from 'nuxt/app'

export default defineNuxtPlugin({
  name: 'better-auth-fetch-plugin',
  enforce: 'pre',
  async setup(nuxtApp: NuxtApp) {
    // Flag if request is cached
    nuxtApp.payload.isCached = Boolean(useRequestEvent()?.context.cache)
    if (nuxtApp.payload.serverRendered && !nuxtApp.payload.prerenderedAt && !nuxtApp.payload.isCached) {
      // Fetch session via our server util so impersonation/ban logic applies on SSR
      const { requireUserSession } = await import('../../server/utils/auth')
      const event = useRequestEvent()
      let serverSession: ServerAuthSession | null = null
      try {
        serverSession = event ? await requireUserSession(event as H3Event) : null
      } catch {
        serverSession = null
      }

      const { session } = useAuth()
      // Convert server AuthSession format to client AuthSession format
      // Both have compatible structures (user and session objects)
      session.value = serverSession ? (serverSession as unknown as AuthSession) : null
      // Access the internal userState ref for mutation
      const userState = useState<AuthUser | null>('auth:user', () => null)
      userState.value = serverSession?.user ? (serverSession.user as unknown as AuthUser) : null
    }
  }
})
