import fs from 'fs/promises'
import path from 'path'
import { getUserFromToken, hasAnyRole } from '../../../../../utils/auth.js'
import { readSubscribers } from '../../../../../utils/newsletter.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-subscribers.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 groupId = getRouterParam(event, 'id')
    
    // Prüfe ob Gruppe existiert und vom Typ 'subscription' ist
    const groups = await readGroups()
    const group = groups.find(g => g.id === groupId)
    
    if (!group) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Newsletter-Gruppe nicht gefunden'
      })
    }

    if (group.type !== 'subscription') {
      throw createError({
        statusCode: 400,
        statusMessage: 'Diese Funktion ist nur für Abonnenten-Newsletter verfügbar'
      })
    }

    // Lade alle Abonnenten
    const subscribers = await readSubscribers()
    
    // Filtere Abonnenten für diese Gruppe
    const groupSubscribers = subscribers
      .filter(s => {
        // Stelle sicher, dass groupIds existiert (für Rückwärtskompatibilität)
        if (!s.groupIds || !Array.isArray(s.groupIds)) {
          return false
        }
        return s.groupIds.includes(groupId)
      })
      .map(s => ({
        id: s.id,
        email: s.email,
        name: s.name || '',
        confirmed: s.confirmed || false,
        subscribedAt: s.subscribedAt || null,
        confirmedAt: s.confirmedAt || null,
        unsubscribedAt: s.unsubscribedAt || null
      }))
      .sort((a, b) => {
        // Sortiere nach bestätigt, dann nach Datum
        if (a.confirmed !== b.confirmed) {
          return a.confirmed ? -1 : 1
        }
        if (a.subscribedAt && b.subscribedAt) {
          return new Date(b.subscribedAt) - new Date(a.subscribedAt)
        }
        return 0
      })

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

