export default defineEventHandler(async (event) => {
  console.log('[LOGOUT] Processing logout request')
  
  try {
    // Check for OIDC session
    const oidcSession = getCookie(event, 'nuxt-oidc-auth')
    
    // Clear OIDC session cookie
    if (oidcSession) {
      deleteCookie(event, 'nuxt-oidc-auth', {
        domain: '.portnimara.dev',
        path: '/'
      })
      console.log('[LOGOUT] OIDC session cleared')
    }
    
    // Always redirect to Keycloak logout to ensure complete logout
    const logoutUrl = 'https://auth.portnimara.dev/realms/client-portal/protocol/openid-connect/logout?' + 
      new URLSearchParams({
        redirect_uri: 'https://client.portnimara.dev/login'
      }).toString()
    
    console.log('[LOGOUT] Redirecting to Keycloak logout:', logoutUrl)
    await sendRedirect(event, logoutUrl)
    
  } catch (error) {
    console.error('[LOGOUT] Logout error:', error)
    
    // Fallback: clear cookies and redirect to login
    try {
      deleteCookie(event, 'nuxt-oidc-auth', {
        domain: '.portnimara.dev',
        path: '/'
      })
    } catch (cookieError) {
      console.error('[LOGOUT] Cookie cleanup error:', cookieError)
    }
    
    await sendRedirect(event, '/login')
  }
})
