// Tenant-scoped audit slice for the customer-admin Security & audit page.
// Proxies GET /tenants/:slug/audit with the signed-in user's access token and
// forwards the filter/pagination params. platform-api enforces tenant
// membership and pins the query to this tenant's slug.

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

const PASS_THROUGH = ['limit', 'q', 'action', 'outcome', 'actorEmail', 'since', 'before'] as const

export default defineEventHandler(async (event) => {
  const session = await getUserSession(event).catch(() => null)
  const accessToken = (session as { accessToken?: string } | null)?.accessToken
  if (!accessToken) {
    throw createError({ statusCode: 401, statusMessage: 'Not signed in' })
  }
  const slug = getRouterParam(event, 'slug')
  const incoming = getQuery(event)
  const query: Record<string, string> = {}
  for (const k of PASS_THROUGH) {
    const v = incoming[k]
    if (v != null && v !== '') query[k] = String(v)
  }
  const base = process.env.PLATFORM_API_INTERNAL_URL ?? 'http://platform-api:3001'
  return $fetch(`${base}/tenants/${slug}/audit`, {
    headers: { Authorization: `Bearer ${accessToken}` },
    query,
  })
})
