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

export default defineEventHandler(async (event) => {
  try {
    const query = getQuery(event)
    const { email, groupId } = query

    if (!email || !groupId) {
      throw createError({
        statusCode: 400,
        statusMessage: 'E-Mail und Gruppen-ID sind erforderlich'
      })
    }

    const ip = getClientIp(event)
    const emailKey = String(email || '').trim().toLowerCase()
    assertRateLimit(event, {
      name: 'newsletter:check:ip',
      keyParts: [ip],
      windowMs: 10 * 60 * 1000,
      maxAttempts: 60,
      lockoutMs: 10 * 60 * 1000
    })
    assertRateLimit(event, {
      name: 'newsletter:check:email',
      keyParts: [emailKey],
      windowMs: 10 * 60 * 1000,
      maxAttempts: 30,
      lockoutMs: 10 * 60 * 1000
    })

    const subscribers = await readSubscribers()
    const emailLower = email.toLowerCase()
    
    const subscriber = subscribers.find(s => {
      const sEmail = (s.email || '').toLowerCase()
      return sEmail === emailLower && s.groupIds && s.groupIds.includes(groupId) && s.confirmed && !s.unsubscribedAt
    })

    return {
      success: true,
      subscribed: !!subscriber
    }
  } catch (error) {
    console.error('Fehler beim Prüfen der Newsletter-Anmeldung:', error)
    if (error.statusCode) {
      throw error
    }
    throw createError({
      statusCode: 500,
      statusMessage: 'Fehler beim Prüfen der Newsletter-Anmeldung'
    })
  }
})

