import { verifyToken, getUserById, hasAnyRole } from '../utils/auth.js'
import { readTermine } from '../utils/termine.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 manage termine
    if (!user || !hasAnyRole(user, 'admin', 'vorstand')) {
      throw createError({
        statusCode: 403,
        message: 'Keine Berechtigung zum Verwalten von Terminen.'
      })
    }

    const termine = await readTermine()

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

