// src/app/(payload)/api/newsletter/confirm/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/confirm?token=<token>
 *
 * Double Opt-In Bestätigung
 * Leitet nach Bestätigung auf eine Erfolgsseite weiter
 */
export async function GET(request: Request): Promise<Response> {
  try {
    const { searchParams } = new URL(request.url)
    const token = searchParams.get('token')

    if (!token) {
      return createRedirectResponse(false, 'Ungültiger Bestätigungs-Link.')
    }

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

    const result = await newsletterService.confirmSubscription(token)

    // Redirect zur Erfolgs- oder Fehlerseite
    // Die Frontend-App sollte diese Routen implementieren
    return createRedirectResponse(result.success, result.message, result.email)
  } catch (error) {
    console.error('[Newsletter Confirm] Error:', error)
    return createRedirectResponse(false, 'Ein Fehler ist aufgetreten.')
  }
}

/**
 * POST /api/newsletter/confirm
 *
 * Double Opt-In Bestätigung (API-Version für AJAX)
 *
 * Body:
 * - token (required): Bestätigungs-Token
 */
export async function POST(request: Request): Promise<Response> {
  try {
    const body = await request.json()
    const token = body.token

    if (!token) {
      return NextResponse.json(
        {
          success: false,
          message: 'Token fehlt.',
        },
        { status: 400 },
      )
    }

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

    const result = await newsletterService.confirmSubscription(token)

    return NextResponse.json(result, {
      status: result.success ? 200 : 400,
    })
  } catch (error) {
    console.error('[Newsletter Confirm] Error:', error)
    return NextResponse.json(
      {
        success: false,
        message: 'Ein Fehler ist aufgetreten.',
      },
      { status: 500 },
    )
  }
}

/**
 * Redirect-Response erstellen
 */
function createRedirectResponse(
  success: boolean,
  message: string,
  email?: string,
): Response {
  const baseUrl = process.env.PAYLOAD_PUBLIC_SERVER_URL || 'https://pl.c2sgmbh.de'

  // Für Browser-Zugriff: HTML-Seite mit Ergebnis anzeigen
  const statusColor = success ? '#4CAF50' : '#f44336'
  const statusIcon = success ? '✓' : '✗'
  const statusTitle = success ? '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;
    }
    .email {
      background: #f5f5f5;
      padding: 12px 20px;
      border-radius: 8px;
      font-family: monospace;
      color: #333;
      margin-bottom: 24px;
      word-break: break-all;
    }
    .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;
    }
  </style>
</head>
<body>
  <div class="card">
    <div class="icon">${statusIcon}</div>
    <h1>${statusTitle}</h1>
    <p>${message}</p>
    ${email ? `<div class="email">${email}</div>` : ''}
    <a href="${baseUrl}" class="button">Zur Startseite</a>
  </div>
</body>
</html>
  `.trim()

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