// src/app/(payload)/api/newsletter/unsubscribe/route.ts

import { NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'
import { createNewsletterService } from '@/lib/email/newsletter-service'

/**
 * GET /api/newsletter/unsubscribe?token=<token>
 *
 * Newsletter abbestellen (Link aus E-Mail)
 * Zeigt eine Bestätigungsseite an
 */
export async function GET(request: Request): Promise<Response> {
  try {
    const { searchParams } = new URL(request.url)
    const token = searchParams.get('token')

    if (!token) {
      return createUnsubscribeResponse(false, 'Ungültiger Abmelde-Link.')
    }

    const payload = await getPayload({ config })
    const newsletterService = createNewsletterService(payload)

    const result = await newsletterService.unsubscribe(token)

    return createUnsubscribeResponse(result.success, result.message)
  } catch (error) {
    console.error('[Newsletter Unsubscribe] Error:', error)
    return createUnsubscribeResponse(false, 'Ein Fehler ist aufgetreten.')
  }
}

/**
 * POST /api/newsletter/unsubscribe
 *
 * Newsletter abbestellen (API-Version für AJAX)
 *
 * Body:
 * - token (required): Token oder Subscriber-ID
 * - email (alternative): E-Mail-Adresse + tenantId
 * - tenantId (optional): Tenant-ID
 */
export async function POST(request: Request): Promise<Response> {
  try {
    const body = await request.json()
    const payload = await getPayload({ config })
    const newsletterService = createNewsletterService(payload)

    // Token-basierte Abmeldung
    if (body.token) {
      const result = await newsletterService.unsubscribe(body.token)
      return NextResponse.json(result, {
        status: result.success ? 200 : 400,
      })
    }

    // E-Mail-basierte Abmeldung (erfordert Tenant-ID)
    if (body.email && body.tenantId) {
      // Subscriber finden
      const subscriber = await payload.find({
        collection: 'newsletter-subscribers',
        where: {
          and: [
            { email: { equals: body.email.toLowerCase() } },
            { tenant: { equals: body.tenantId } },
          ],
        },
        limit: 1,
      })

      if (subscriber.docs.length === 0) {
        return NextResponse.json(
          {
            success: false,
            message: 'E-Mail-Adresse nicht gefunden.',
          },
          { status: 404 },
        )
      }

      const result = await newsletterService.unsubscribe(String(subscriber.docs[0].id))
      return NextResponse.json(result, {
        status: result.success ? 200 : 400,
      })
    }

    return NextResponse.json(
      {
        success: false,
        message: 'Token oder E-Mail-Adresse fehlt.',
      },
      { status: 400 },
    )
  } catch (error) {
    console.error('[Newsletter Unsubscribe] Error:', error)
    return NextResponse.json(
      {
        success: false,
        message: 'Ein Fehler ist aufgetreten.',
      },
      { status: 500 },
    )
  }
}

/**
 * Unsubscribe-Response erstellen (HTML-Seite)
 */
function createUnsubscribeResponse(success: boolean, message: string): Response {
  const baseUrl = process.env.PAYLOAD_PUBLIC_SERVER_URL || 'https://pl.c2sgmbh.de'

  const statusColor = success ? '#4CAF50' : '#f44336'
  const statusIcon = success ? '✓' : '✗'
  const statusTitle = success ? 'Abmeldung erfolgreich' : 'Fehler'

  const html = `
<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Newsletter - ${statusTitle}</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      padding: 20px;
    }
    .card {
      background: white;
      border-radius: 16px;
      padding: 48px;
      max-width: 480px;
      width: 100%;
      text-align: center;
      box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    }
    .icon {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      background: ${statusColor};
      color: white;
      font-size: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 auto 24px;
    }
    h1 {
      color: #333;
      font-size: 24px;
      margin-bottom: 16px;
    }
    p {
      color: #666;
      line-height: 1.6;
      margin-bottom: 24px;
    }
    .button {
      display: inline-block;
      background: #667eea;
      color: white;
      text-decoration: none;
      padding: 14px 32px;
      border-radius: 8px;
      font-weight: 600;
      transition: background 0.2s;
    }
    .button:hover {
      background: #5a6fd6;
    }
    .secondary-text {
      margin-top: 24px;
      font-size: 14px;
      color: #999;
    }
  </style>
</head>
<body>
  <div class="card">
    <div class="icon">${statusIcon}</div>
    <h1>${statusTitle}</h1>
    <p>${message}</p>
    <a href="${baseUrl}" class="button">Zur Startseite</a>
    ${success ? '<p class="secondary-text">Sie können sich jederzeit erneut anmelden.</p>' : ''}
  </div>
</body>
</html>
  `.trim()

  return new Response(html, {
    status: 200,
    headers: {
      'Content-Type': 'text/html; charset=utf-8',
    },
  })
}
