/**
 * 認證 Session Provider
 */
'use client'

import { useEffect } from 'react'
import { SessionProvider as NextAuthSessionProvider, useSession, signOut } from 'next-auth/react'

/**
 * Session Monitor - 監控 Keycloak token refresh 狀態
 */
function SessionMonitor({ children }: { children: React.ReactNode }) {
  const { data: session, status } = useSession()

  useEffect(() => {
    // 如果 session 有 RefreshTokenError，強制登出
    if (status === 'authenticated' && (session as any)?.error === 'RefreshTokenError') {
      console.error('[SessionMonitor] Keycloak refresh token expired - forcing logout')
      signOut({ callbackUrl: '/auth/signin' })
    }
  }, [session, status])

  return <>{children}</>
}

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