// Mount the nuxt-oidc-auth session store on Redis when configured.
//
// The module persists sessions via useStorage('oidc'); the default mount is
// per-pod memory, which 401s every request that lands on a replica that
// didn't mint the session AND drops all sessions on each deploy. Mounting at
// runtime (instead of nitro.storage in nuxt.config) keeps the Redis URL out
// of the build — same reason the OIDC provider config is env-driven.
//
// SESSION_REDIS_URL is set in production (fleet/apps/portal.yaml, value in
// portal-secrets). Unset in dev → in-memory mount stays, no Redis needed.
import redisDriver from 'unstorage/drivers/redis'

export default defineNitroPlugin(async () => {
  const url = process.env.SESSION_REDIS_URL
  if (!url) return
  const storage = useStorage()
  // The module ships its own build-time 'oidc' mount (memory driver) — it
  // must be unmounted first or mount() throws 'already mounted at oidc:'.
  await storage.unmount('oidc')
  storage.mount(
    'oidc',
    redisDriver({
      url,
      base: 'oidc:portal',
      // Safety net against orphaned sessions accumulating forever; well above
      // any real session lifetime.
      ttl: 60 * 60 * 24 * 14,
    }),
  )
})
