import { readSubscribers, writeSubscribers } from '../../utils/newsletter.js'
import { assertRateLimit, getClientIp, registerRateLimitFailure, registerRateLimitSuccess } from '../../utils/rate-limit.js'

export default defineEventHandler(async (event) => {
  try {
    const query = getQuery(event)
    const token = query.token

    if (!token) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Abmeldetoken fehlt'
      })
    }

    const ip = getClientIp(event)
    const tokenKey = String(token || '').trim()
    assertRateLimit(event, {
      name: 'newsletter:unsubscribe-token:ip',
      keyParts: [ip],
      windowMs: 10 * 60 * 1000,
      maxAttempts: 60,
      lockoutMs: 10 * 60 * 1000
    })
    assertRateLimit(event, {
      name: 'newsletter:unsubscribe-token:token',
      keyParts: [tokenKey],
      windowMs: 10 * 60 * 1000,
      maxAttempts: 10,
      lockoutMs: 30 * 60 * 1000
    })

    const subscribers = await readSubscribers()
    const subscriber = subscribers.find(s => s.unsubscribeToken === token)

    if (!subscriber) {
      await registerRateLimitFailure(event, { name: 'newsletter:unsubscribe-token:token', keyParts: [tokenKey] })
      throw createError({
        statusCode: 404,
        statusMessage: 'Ungültiger Abmeldetoken'
      })
    }

    if (subscriber.unsubscribedAt) {
      // Bereits abgemeldet
      return sendRedirect(event, '/newsletter/unsubscribed?already=true')
    }

    // Abmeldung durchführen
    subscriber.unsubscribedAt = new Date().toISOString()
    subscriber.confirmed = false
    
    // Stelle sicher, dass groupIds existiert (für Rückwärtskompatibilität)
    if (!subscriber.groupIds) {
      subscriber.groupIds = []
    }
    // Leere groupIds, um von allen Gruppen abzumelden
    subscriber.groupIds = []

    await writeSubscribers(subscribers)

    registerRateLimitSuccess(event, { name: 'newsletter:unsubscribe-token:token', keyParts: [tokenKey] })
    // Weiterleitung zur Abmelde-Bestätigungsseite
    return sendRedirect(event, '/newsletter/unsubscribed')
  } catch (error) {
    console.error('Fehler bei Newsletter-Abmeldung:', error)
    if (error.statusCode) {
      throw error
    }
    throw createError({
      statusCode: 500,
      statusMessage: 'Fehler bei der Newsletter-Abmeldung'
    })
  }
})

