import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { newsletterSubscribeSchema, validateRequest } from '@/lib/validationSchemas';
import { rateLimit, getClientIdentifier, RateLimits } from '@/lib/rateLimit';
import { sendNewsletterWelcomeEmail } from '@/lib/email';

/**
 * POST /api/newsletter/subscribe
 * Subscribe to AI features newsletter
 * Public endpoint - no authentication required
 */
export async function POST(request: NextRequest) {
  try {
    // Get client identifier for rate limiting
    const clientId = getClientIdentifier(request);

    // Apply rate limiting (5 per hour)
    const rateLimitResult = rateLimit(clientId, RateLimits.NEWSLETTER_SUBSCRIBE);

    if (!rateLimitResult.success) {
      return NextResponse.json(
        {
          error: 'Too many subscription attempts. Please try again later.',
          retryAfter: Math.ceil((rateLimitResult.reset - Date.now()) / 1000),
        },
        {
          status: 429,
          headers: {
            'X-RateLimit-Limit': rateLimitResult.limit.toString(),
            'X-RateLimit-Remaining': rateLimitResult.remaining.toString(),
            'X-RateLimit-Reset': rateLimitResult.reset.toString(),
            'Retry-After': Math.ceil((rateLimitResult.reset - Date.now()) / 1000).toString(),
          },
        }
      );
    }

    // Parse and validate request body
    const body = await request.json();
    const validation = await validateRequest(newsletterSubscribeSchema, body);

    if (!validation.success) {
      return NextResponse.json(validation.error, { status: 400 });
    }

    const { email } = validation.data;

    // Check if email already subscribed
    const existing = await db.newsletterSubscription.findUnique({
      where: { email },
    });

    if (existing) {
      // If already subscribed, return success (idempotent)
      // Don't reveal if email exists for privacy
      return NextResponse.json({
        success: true,
        message: 'Successfully subscribed to AI features newsletter!',
        alreadySubscribed: true,
      });
    }

    // Create new subscription
    await db.newsletterSubscription.create({
      data: {
        email,
        source: 'ai-coming-soon',
        status: 'subscribed',
      },
    });

    // Send welcome email (don't block response)
    sendNewsletterWelcomeEmail(email).catch((error) => {
      console.error('Failed to send welcome email (non-blocking):', error);
    });

    return NextResponse.json({
      success: true,
      message: 'Successfully subscribed to AI features newsletter!',
      alreadySubscribed: false,
    });
  } catch (error) {
    console.error('Newsletter subscription error:', error);
    return NextResponse.json(
      {
        error: 'Failed to subscribe to newsletter. Please try again.',
      },
      { status: 500 }
    );
  }
}
