'use client'

import { SessionProvider as NextAuthSessionProvider, signOut, useSession } from "next-auth/react"
import { useEffect, useRef } from "react"
import { usePathname } from "next/navigation"

/** 检测会话失效并自动登出 */
function SessionInvalidationGuard({ children }: { children: React.ReactNode }) {
  const { data: session, status } = useSession()
  const pathname = usePathname()
  const signingOut = useRef(false)

  useEffect(() => {
    // 已认证但 session 中没有 user（会话被标记失效），自动登出清除 cookie
    if (status === 'authenticated' && !(session as any)?.user?.id && !signingOut.current && pathname !== '/login') {
      signingOut.current = true
      signOut({ callbackUrl: '/login' })
    }
  }, [status, session, pathname])

  return <>{children}</>
}

export function SessionProvider({ children }: { children: React.ReactNode }) {
  return (
    <NextAuthSessionProvider>
      <SessionInvalidationGuard>
        {children}
      </SessionInvalidationGuard>
    </NextAuthSessionProvider>
  )
}
