// Sign-out. Ends both the portal session and the Authentik IdP session so
// "Sign in again" always requires fresh credentials — even for the next
// person at the same browser.
//
// Flow:
//   1. Read the id_token off the local session (needed as id_token_hint).
//   2. Clear the local nuxt-oidc-auth session (cookie + persistent store).
//   3. 302 the BROWSER to Authentik's end-session endpoint with
//      post_logout_redirect_uri=/signed-out.
//
// Why the browser redirect (not server-to-server):
// Authentik's session cookie lives on auth.dezky.local. Only a response
// FROM that host can set/clear it — a server-side fetch invalidates the
// session record but leaves the browser cookie intact, so the next OIDC
// authorize succeeds silently. A 302 through Authentik fixes that: the
// browser visits auth.dezky.local, receives Set-Cookie clearing the
// session, then bounces back to /signed-out (the URL is in the provider's
// redirect_uris list — see infrastructure setup).
//
// The brief URL-bar flash through auth.dezky.local is acceptable: no
// Authentik UI renders (it's a redirect chain), and the Traefik middleware
// on the authentik service would catch any stray landing on the dashboard
// anyway.

import { getUserSession, clearUserSession } from 'nuxt-oidc-auth/runtime/server/utils/session.js'

const END_SESSION = 'https://auth.dezky.local/application/o/dezky-portal/end-session/'
const POST_LOGOUT_REDIRECT = 'https://app.dezky.local/signed-out'

export default defineEventHandler(async (event) => {
  const session = await getUserSession(event).catch(() => ({} as any))
  const idToken: string | undefined = (session as any).idToken

  await clearUserSession(event).catch(() => {})

  const params = new URLSearchParams({
    post_logout_redirect_uri: POST_LOGOUT_REDIRECT,
    ...(idToken && { id_token_hint: idToken }),
  })

  return sendRedirect(event, `${END_SESSION}?${params.toString()}`, 302)
})
