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

function getEncryptionKey() {
  return process.env.ENCRYPTION_KEY || 'local_development_encryption_key_change_in_production'
}

// Prüft ob Daten verschlüsselt sind
function isEncrypted(data) {
  try {
    const parsed = JSON.parse(data.trim())
    if (Array.isArray(parsed)) {
      return false
    }
    if (typeof parsed === 'object' && parsed !== null && !parsed.encryptedData) {
      return false
    }
    return false
  } catch (_e) {
    return true
  }
}

async function readPosts() {
  try {
    const data = await fs.readFile(NEWSLETTER_POSTS_FILE, 'utf-8')
    const encrypted = isEncrypted(data)
    
    if (encrypted) {
      const encryptionKey = getEncryptionKey()
      try {
        return decryptObject(data, encryptionKey)
      } catch (decryptError) {
        console.error('Fehler beim Entschlüsseln der Newsletter-Posts:', decryptError)
        try {
          const plainData = JSON.parse(data)
          console.warn('Entschlüsselung fehlgeschlagen, versuche als unverschlüsseltes Format zu lesen')
          return plainData
        } catch (_parseError) {
          console.error('Konnte Newsletter-Posts weder entschlüsseln noch als JSON lesen')
          return []
        }
      }
    } else {
      // Plain JSON - migriere zu verschlüsselter Speicherung
      const posts = JSON.parse(data)
      console.log('Migriere unverschlüsselte Newsletter-Posts zu verschlüsselter Speicherung...')
      // Schreiben wird hier nicht gemacht, da wir nur lesen
      return posts
    }
  } 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 groupId = getRouterParam(event, 'id')
    const posts = await readPosts()
    
    // Filtere Posts nach Gruppe und sortiere nach Datum (neueste zuerst)
    const groupPosts = posts
      .filter(p => p.groupId === groupId)
      .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))

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