import { readNews } from '../utils/news.js'

export default defineEventHandler(async (event) => {
  try {
    const allNews = await readNews()
    const now = new Date()

    // Filter only public news that are not hidden and not expired
    const publicNews = allNews.filter(item => {
      // Must be public
      if (!item.isPublic) return false
      
      // Must not be hidden
      if (item.isHidden) return false
      
      // Must not be expired
      if (item.expiresAt) {
        const expiresAt = new Date(item.expiresAt)
        if (expiresAt <= now) return false
      }
      
      return true
    })

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

    // Limit to latest 3 for homepage
    const latestNews = publicNews.slice(0, 3)

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

