import fs from 'fs/promises'
import path from 'path'
import { getUserFromToken } 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 {
    // Prüfe ob Benutzer eingeloggt ist
    let isLoggedIn = false
    try {
      const token = getCookie(event, 'auth_token') || getHeader(event, 'authorization')?.replace('Bearer ', '')
      if (token) {
        const user = await getUserFromToken(token)
        if (user && user.active) {
          isLoggedIn = true
        }
      }
    } catch (_e) {
      // Nicht eingeloggt - kein Problem
    }

    const groups = await readGroups()
    
    // Filtere Newsletter-Gruppen basierend auf Login-Status
    let publicGroups
    if (isLoggedIn) {
      // Eingeloggte Benutzer sehen alle Abonnenten-Newsletter (intern und extern)
      publicGroups = groups.filter(g => g.type === 'subscription')
    } else {
      // Nicht eingeloggte Benutzer sehen nur externe Newsletter
      publicGroups = groups.filter(g => 
        g.type === 'subscription' && g.sendToExternal === true
      )
    }
    
    return {
      success: true,
      groups: publicGroups.map(g => ({
        id: g.id,
        name: g.name,
        description: g.description || ''
      }))
    }
  } catch (error) {
    console.error('Fehler beim Laden der öffentlichen Newsletter-Gruppen:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'Fehler beim Laden der Newsletter-Gruppen'
    })
  }
})

