import { verifyToken } from '../utils/auth.js'
import { readNews } 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 news = await readNews()

    // Sort by created date, newest first
    news.sort((a, b) => new Date(b.created) - new Date(a.created))

    return {
      success: true,
      news
    }
  } catch (error) {
    console.error('Fehler beim Abrufen der News:', error)
    throw error
  }
})

