// Set the DMARC policy for a domain (wizard step 5). Proxies
// PATCH /tenants/:slug/domains/:domain/dmarc with { dmarcPolicy };
// platform-api updates the expected record, re-verifies, and enforces membership.

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

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 domain = getRouterParam(event, 'domain')
  const body = await readBody(event)
  const base = process.env.PLATFORM_API_INTERNAL_URL ?? 'http://platform-api:3001'
  return $fetch(`${base}/tenants/${slug}/domains/${encodeURIComponent(domain ?? '')}/dmarc`, {
    method: 'PATCH',
    headers: { Authorization: `Bearer ${accessToken}` },
    body,
  })
})
