import fs from 'fs/promises'
import path from 'path'
import { getUserFromToken, hasAnyRole } from '../../utils/auth.js'

// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
// filename is always a hardcoded constant (e.g., 'newsletter.json'), never user input
const getDataPath = (filename) => {
  const cwd = process.cwd()
  if (cwd.endsWith('.output')) {
    // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
    return path.join(cwd, '../server/data', filename)
  }
    // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
  return path.join(cwd, 'server/data', filename)
}

const NEWSLETTERS_FILE = getDataPath('newsletters.json')

async function readNewsletters() {
  try {
    const data = await fs.readFile(NEWSLETTERS_FILE, 'utf-8')
    return JSON.parse(data)
  } catch (error) {
    if (error.code === 'ENOENT') {
      return []
    }
    throw error
  }
}

export default defineEventHandler(async (event) => {
  try {
    // Authentifizierung prüfen
    const token = getCookie(event, 'auth_token') || getHeader(event, 'authorization')?.replace('Bearer ', '')
    
    if (!token) {
      throw createError({
        statusCode: 401,
        statusMessage: 'Nicht authentifiziert'
      })
    }

    const user = await getUserFromToken(token)
    if (!user || !hasAnyRole(user, 'admin', 'vorstand', 'newsletter')) {
      throw createError({
        statusCode: 403,
        statusMessage: 'Keine Berechtigung'
      })
    }

    const newsletters = await readNewsletters()
    
    // Sortiere nach Erstellungsdatum (neueste zuerst)
    newsletters.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))

    return {
      success: true,
      newsletters
    }
  } catch (error) {
    console.error('Fehler beim Laden der Newsletter:', error)
    if (error.statusCode) {
      throw error
    }
    throw createError({
      statusCode: 500,
      statusMessage: 'Fehler beim Laden der Newsletter'
    })
  }
})

