// Add an email domain. Proxies POST /tenants/:slug/domains with { domain };
// platform-api provisions it in Stalwart (auto-generating DKIM), seeds the
// expected records, runs an initial DNS check, and enforces tenant 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 body = await readBody(event)
  const base = process.env.PLATFORM_API_INTERNAL_URL ?? 'http://platform-api:3001'
  return $fetch(`${base}/tenants/${slug}/domains`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${accessToken}` },
    body,
  })
})
