import { verifyToken, getUserById, hasAnyRole } from '../utils/auth.js'
import { saveNews } from '../utils/news.js'

export default defineEventHandler(async (event) => {
  try {
    const token = getCookie(event, 'auth_token')

    if (!token) {
      throw createError({
        statusCode: 401,
        message: 'Nicht authentifiziert.'
      })
    }

    const decoded = verifyToken(token)

    if (!decoded) {
      throw createError({
        statusCode: 401,
        message: 'Ungültiges Token.'
      })
    }

    const user = await getUserById(decoded.id)

    // Only admin and vorstand can create/edit news
    if (!user || !hasAnyRole(user, 'admin', 'vorstand')) {
      throw createError({
        statusCode: 403,
        message: 'Keine Berechtigung zum Erstellen/Bearbeiten von News.'
      })
    }

    const body = await readBody(event)
    const { id, title, content, isPublic, expiresAt, isHidden } = body

    if (!title || !content) {
      throw createError({
        statusCode: 400,
        message: 'Titel und Inhalt sind erforderlich.'
      })
    }

    await saveNews({
      id: id || undefined,
      title,
      content,
      isPublic: isPublic || false,
      expiresAt: expiresAt || undefined,
      isHidden: isHidden || false,
      author: user.name
    })

    return {
      success: true,
      message: 'News erfolgreich gespeichert.'
    }
  } catch (error) {
    console.error('Fehler beim Speichern der News:', error)
    throw error
  }
})

