// 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'
import { createApiErrorResponse } from '@/lib/security'
import {
  asObject,
  optionalString,
  optionalNumber,
  validateJsonBody,
  validationIssue,
  validationErrorResponse,
  type ApiValidationResult,
} from '@/lib/validation'

interface UnsubscribeBody {
  token?: string
  email?: string
  tenantId?: number
}

function validateUnsubscribeBody(input: unknown): ApiValidationResult<UnsubscribeBody> {
  const objectResult = asObject(input)
  if (!objectResult.valid) {
    return objectResult as ApiValidationResult<UnsubscribeBody>
  }

  const tokenResult = optionalString(objectResult.data, 'token')
  const emailResult = optionalString(objectResult.data, 'email')
  const tenantResult = optionalNumber(objectResult.data, 'tenantId')

  if (!tokenResult.valid || !emailResult.valid || !tenantResult.valid) {
    return {
      valid: false,
      issues: [
        ...(tokenResult.valid ? [] : tokenResult.issues),
        ...(emailResult.valid ? [] : emailResult.issues),
        ...(tenantResult.valid ? [] : tenantResult.issues),
      ],
    }
  }

  if (!tokenResult.data && !(emailResult.data && tenantResult.data !== undefined)) {
    return {
      valid: false,
      issues: [
        validationIssue(
          'token|email+tenantId',
          'required',
          'Either token or email+tenantId must be provided',
        ),
      ],
    }
  }

  return {
    valid: true,
    data: {
      token: tokenResult.data,
      email: emailResult.data,
      tenantId: tenantResult.data,
    },
  }
}

/**
 * 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): Unsubscribe-Token
 * - email (alternative): E-Mail-Adresse + tenantId
 * - tenantId (optional): Tenant-ID
 */
export async function POST(request: Request): Promise<Response> {
  try {
    const bodyResult = await validateJsonBody(request, validateUnsubscribeBody)
    if (!bodyResult.valid) {
      return validationErrorResponse(bodyResult.issues)
    }

    const body = bodyResult.data
    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 !== undefined) {
      // 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 foundSubscriber = subscriber.docs[0] as {
        id: number
        confirmationToken?: string | null
      }

      let actionToken = foundSubscriber.confirmationToken || null
      if (!actionToken) {
        actionToken = crypto.randomUUID()
        await payload.update({
          collection: 'newsletter-subscribers',
          id: foundSubscriber.id,
          data: {
            confirmationToken: actionToken,
          },
          overrideAccess: true,
        })
      }

      const result = await newsletterService.unsubscribe(actionToken)
      return NextResponse.json(result, {
        status: result.success ? 200 : 400,
      })
    }
    return createApiErrorResponse(
      400,
      'VALIDATION_FAILED',
      'Token oder E-Mail-Adresse fehlt.',
    )
  } 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',
    },
  })
}
