import SiteContent from '../../../models/siteContent.js'
import { requireAdmin } from '../../../utils/auth.js'
import { validateBody } from '../../../utils/validateBody.js'
import { SITE_CONTENT_KEYS, siteContentUpsertSchema } from '../../../utils/schemas.js'

export default defineEventHandler(async (event) => {
  await requireAdmin(event)

  const key = getRouterParam(event, 'key')
  if (!SITE_CONTENT_KEYS.includes(key)) {
    throw createError({ statusCode: 404, statusMessage: 'Unknown content key' })
  }

  const body = await validateBody(event, siteContentUpsertSchema)

  const doc = await SiteContent.findOneAndUpdate(
    { key },
    { $set: { title: body.title || '', body: body.body || '' } },
    { upsert: true, new: true, runValidators: true }
  ).lean()

  return {
    key: doc.key,
    title: doc.title || '',
    body: doc.body || '',
    updatedAt: doc.updatedAt || null
  }
})
