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-groups.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 NEWSLETTER_GROUPS_FILE = getDataPath('newsletter-groups.json')

async function readGroups() {
  try {
    const data = await fs.readFile(NEWSLETTER_GROUPS_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 groups = await readGroups()
    
    return {
      success: true,
      groups
    }
  } catch (error) {
    console.error('Fehler beim Laden der Newsletter-Gruppen:', error)
    if (error.statusCode) {
      throw error
    }
    throw createError({
      statusCode: 500,
      statusMessage: 'Fehler beim Laden der Newsletter-Gruppen'
    })
  }
})

