// Authorization gate for the operator portal.
//
// nuxt-oidc-auth's global middleware only proves *authentication* — "does
// this browser hold a valid dezky-operator session?". It says nothing about
// whether the person is actually an operator. Without this middleware, anyone
// who completes the dezky-operator OIDC flow (a partner, a tenant admin, any
// Authentik user) lands on the full operator shell. The platform-api still
// 403s their data calls via OperatorGuard, but *being on the operator app at
// all* is the violation — and it leaves only the Authentik application policy
// standing between a non-admin and the UI. This is the second, in-app layer.
//
// Runs after 00.auth.global (nuxt-oidc-auth), so by the time we get here the
// session exists. We resolve the operator's own profile and require
// platformAdmin=true. A signed-in non-admin is fully signed out (local +
// Authentik IdP) — never silently left with a live operator session on what
// may be a shared workstation — and shown /not-authorized.
//
// /api/me is SSR-safe via useRequestFetch (it forwards the session cookie),
// so there's no flash of operator chrome before the redirect.

export default defineNuxtRouteMiddleware(async (to) => {
  // Public surfaces: the login bounce, the sign-out landing, and the
  // not-authorized page itself must stay reachable without the check.
  if (
    to.path.startsWith('/auth/') ||
    to.path === '/signed-out' ||
    to.path === '/not-authorized'
  ) {
    return
  }

  const { fetchMe, isPlatformAdmin } = useMe()
  const me = await fetchMe()

  // fetchMe() collapses every failure to null — both "not signed in" and
  // "signed in, but /api/me (→ platform-api) errored transiently". We let BOTH
  // through here. The not-signed-in case is handled by the OIDC middleware's
  // bounce to login. The API-error case is a DELIBERATE fail-OPEN: failing
  // closed would bounce every operator to /not-authorized — and thus fully
  // sign them out — on any platform-api restart, a self-inflicted mass-signout
  // on routine deploys. The exposure from failing open is contained by the
  // other two layers: Authentik's application policy stops a non-admin from
  // ever obtaining a session (layer 1), and OperatorGuard 403s every data call
  // regardless of what the UI renders (layer 3). See docs/AUTHENTIK-SETUP.md →
  // "Operator portal isolation". (The partner middleware fails CLOSED instead
  // because the partner surface has no layer-1 IdP gate.)
  if (!me) return

  if (!isPlatformAdmin.value) {
    return navigateTo('/not-authorized')
  }
})
