import { useEffect, useState } from 'react' import { formatAuthError } from '../lib/authError' import { getAuthSession, logout, type AuthSession } from '../services/api/auth' const signedOutSession: AuthSession = { authentication_required: true, authenticated: false, username: null, expires_at: null, role: null, guest_access_enabled: false, guest_project_id: null, } export function useOperatorSession() { const [session, setSession] = useState(null) const [sessionError, setSessionError] = useState(null) const [loggingOut, setLoggingOut] = useState(false) useEffect(() => { let active = true getAuthSession() .then((value) => { if (active) { setSession(value) setSessionError(null) } }) .catch((error) => { if (active) { setSession(signedOutSession) setSessionError(formatAuthError(error, 'De aanmeldservice is tijdelijk niet bereikbaar. Probeer het over enkele ogenblikken opnieuw.')) } }) return () => { active = false } }, []) useEffect(() => { const expireSession = () => { setSession((current) => ({ ...signedOutSession, guest_access_enabled: current?.guest_access_enabled ?? false, })) setSessionError('Uw sessie is verlopen. Meld u opnieuw aan.') } window.addEventListener('geointel:session-expired', expireSession) return () => window.removeEventListener('geointel:session-expired', expireSession) }, []) const handleLogout = async () => { setLoggingOut(true) try { setSession(await logout()) setSessionError(null) } catch (error) { setSessionError(formatAuthError(error, 'Uitloggen is niet gelukt. Vernieuw de pagina en probeer opnieuw.')) } finally { setLoggingOut(false) } } const handleAuthenticated = (authenticatedSession: AuthSession) => { setSession(authenticatedSession) setSessionError(null) } return { session, sessionError, loggingOut, handleAuthenticated, handleLogout } }