export default defineEventHandler(async (event) => {
  try {
    const sessionCookie = getCookie(event, 'keycloak-session')
    
    if (!sessionCookie) {
      return { user: null, authenticated: false }
    }

    const sessionData = JSON.parse(sessionCookie)
    
    // Check if session is still valid
    if (sessionData.expiresAt && Date.now() > sessionData.expiresAt) {
      // Session expired, clear cookie
      deleteCookie(event, 'keycloak-session')
      return { user: null, authenticated: false }
    }

    return {
      user: {
        id: sessionData.user.sub,
        email: sessionData.user.email,
        username: sessionData.user.preferred_username,
        name: sessionData.user.name || sessionData.user.preferred_username
      },
      authenticated: true
    }
  } catch (error) {
    console.error('[KEYCLOAK] Session check error:', error)
    // Clear invalid session
    deleteCookie(event, 'keycloak-session')
    return { user: null, authenticated: false }
  }
})
