import { getUserFromToken, hasAnyRole } from '../../../../utils/auth.js'
import { readContactRequests, updateContactRequestStatus } from '../../../../utils/contact-requests.js'

export default defineEventHandler(async (event) => {
  const token = getCookie(event, 'auth_token')
  const currentUser = token ? await getUserFromToken(token) : null

  if (!currentUser || !hasAnyRole(currentUser, 'admin', 'vorstand', 'trainer')) {
    throw createError({
      statusCode: 403,
      statusMessage: 'Zugriff verweigert'
    })
  }

  const requestId = getRouterParam(event, 'id')
  if (!requestId) {
    throw createError({ statusCode: 400, statusMessage: 'Anfrage-ID fehlt' })
  }

  const all = await readContactRequests()
  const target = all.find((r) => r.id === requestId)
  if (!target) {
    throw createError({ statusCode: 404, statusMessage: 'Anfrage nicht gefunden' })
  }

  const newStatus = target.status === 'beantwortet' ? 'offen' : 'beantwortet'
  const updated = await updateContactRequestStatus(requestId, newStatus)

  return {
    success: true,
    request: updated
  }
})
