import fs from 'fs/promises'
import path from 'path'
import { decryptObject } from '../../utils/encryption.js'

export default defineEventHandler(async (event) => {
  try {
    // Nur Vorstand oder Admin darf Mitgliedschaftsantraege lesen
    const token = getCookie(event, 'auth_token')
    const currentUser = token ? await getUserFromToken(token) : null
    if (!currentUser || !hasAnyRole(currentUser, 'admin', 'vorstand')) {
      throw createError({ statusCode: 403, statusMessage: 'Zugriff verweigert' })
    }

    const config = useRuntimeConfig()
    const encryptionKey = config.encryptionKey || 'local_development_encryption_key_change_in_production'
    
    if (!encryptionKey) {
      throw createError({
        statusCode: 500,
        statusMessage: 'Verschlüsselungsschlüssel nicht konfiguriert'
      })
    }
    
    const dataDir = path.join(process.cwd(), 'server/data/membership-applications')
    
    // Prüfen ob Verzeichnis existiert
    try {
      await fs.access(dataDir)
    } catch {
      return []
    }
    
    // Alle Anträge laden
    const files = await fs.readdir(dataDir)
    const applications = []
    
    for (const file of files) {
      if (file.endsWith('.json')) {
        try {
          const filePath = path.join(dataDir, file)
          const fileContent = await fs.readFile(filePath, 'utf8')
          const applicationData = JSON.parse(fileContent)
          
          // Prüfe ob Daten verschlüsselt oder unverschlüsselt sind
          if (applicationData.personalData) {
            // Unverschlüsselte Daten (neues Format)
            applications.push({
              id: applicationData.id,
              timestamp: applicationData.timestamp,
              status: applicationData.status,
              metadata: applicationData.metadata,
              personalData: applicationData.personalData
            })
          } else if (applicationData.encryptedData) {
            // Verschlüsselte Daten (altes Format)
            const decryptedData = decryptObject(applicationData.encryptedData, encryptionKey)
            applications.push({
              id: applicationData.id,
              timestamp: applicationData.timestamp,
              status: applicationData.status,
              metadata: applicationData.metadata,
              personalData: {
                nachname: decryptedData.nachname,
                vorname: decryptedData.vorname,
                email: decryptedData.email,
                telefon_privat: decryptedData.telefon_privat,
                telefon_mobil: decryptedData.telefon_mobil
              }
            })
          }
        } catch (error) {
          // nosemgrep: javascript.lang.security.audit.unsafe-formatstring.unsafe-formatstring
          // file is from readdir, not user input; error.message is safe
          // nosemgrep: javascript.lang.security.audit.unsafe-formatstring.unsafe-formatstring
          console.error(`Fehler beim Laden von ${file}:`, error.message)
        }
      }
    }
    
    // Nach Zeitstempel sortieren (neueste zuerst)
    applications.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
    
  return applications
    
  } catch (error) {
    console.error('Fehler beim Laden der Mitgliedschaftsanträge:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'Fehler beim Laden der Anträge'
    })
  }
})
