import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { db } from '@/lib/db';
import { sendAIFeatureLaunchEmail } from '@/lib/email';
import { rateLimit, RateLimits } from '@/lib/rateLimit';

/**
 * POST /api/newsletter/broadcast
 * Send AI feature launch email to all subscribed users
 * PROTECTED: Only authenticated users can access (you may want to add admin check)
 */
export async function POST(request: NextRequest) {
  try {
    // Check authentication using newsletter-admin cookie
    const adminCookie = cookies().get('newsletter-admin')?.value;

    if (adminCookie !== 'authenticated') {
      return NextResponse.json(
        { error: 'Unauthorized. Please log in.' },
        { status: 401 }
      );
    }

    // Optional: Add admin check here
    // const user = await db.user.findUnique({ where: { id: userId } });
    // if (user?.role !== 'ADMIN') {
    //   return NextResponse.json({ error: 'Forbidden. Admin access required.' }, { status: 403 });
    // }

    // Rate limiting (prevent accidental spam)
    const rateLimitResult = rateLimit('newsletter-admin', {
      name: 'newsletter-broadcast',
      maxRequests: 2, // Only 2 broadcasts per hour
      windowSeconds: 60 * 60,
    });

    if (!rateLimitResult.success) {
      return NextResponse.json(
        {
          error: 'Too many broadcast attempts. Please wait before trying again.',
          retryAfter: Math.ceil((rateLimitResult.reset - Date.now()) / 1000),
        },
        { status: 429 }
      );
    }

    // Get all subscribed users
    const subscribers = await db.newsletterSubscription.findMany({
      where: {
        status: 'subscribed',
      },
      select: {
        email: true,
      },
    });

    if (subscribers.length === 0) {
      return NextResponse.json({
        success: true,
        message: 'No subscribers found',
        sent: 0,
      });
    }

    // Send emails in batches to avoid overwhelming Resend
    const batchSize = 10;
    const results = {
      sent: 0,
      failed: 0,
      errors: [] as string[],
    };

    for (let i = 0; i < subscribers.length; i += batchSize) {
      const batch = subscribers.slice(i, i + batchSize);

      // Send emails in parallel within batch
      const promises = batch.map(async (subscriber) => {
        try {
          await sendAIFeatureLaunchEmail(subscriber.email);
          results.sent++;
        } catch (error) {
          results.failed++;
          results.errors.push(`Failed to send to ${subscriber.email}`);
          console.error(`Failed to send to ${subscriber.email}:`, error);
        }
      });

      await Promise.allSettled(promises);

      // Small delay between batches to be nice to the email service
      if (i + batchSize < subscribers.length) {
        await new Promise((resolve) => setTimeout(resolve, 1000));
      }
    }

    return NextResponse.json({
      success: true,
      message: `Broadcast completed. Sent to ${results.sent} subscribers.`,
      sent: results.sent,
      failed: results.failed,
      total: subscribers.length,
      errors: results.errors.length > 0 ? results.errors : undefined,
    });
  } catch (error) {
    console.error('Newsletter broadcast error:', error);
    return NextResponse.json(
      {
        error: 'Failed to send broadcast emails. Please try again.',
      },
      { status: 500 }
    );
  }
}

/**
 * GET /api/newsletter/broadcast
 * Get subscriber count and preview
 * PROTECTED: Only authenticated users
 */
export async function GET(request: NextRequest) {
  try {
    // Check authentication using newsletter-admin cookie
    const adminCookie = cookies().get('newsletter-admin')?.value;

    if (adminCookie !== 'authenticated') {
      return NextResponse.json(
        { error: 'Unauthorized. Please log in.' },
        { status: 401 }
      );
    }

    const subscriberCount = await db.newsletterSubscription.count({
      where: {
        status: 'subscribed',
      },
    });

    const recentSubscribers = await db.newsletterSubscription.findMany({
      where: {
        status: 'subscribed',
      },
      select: {
        email: true,
        createdAt: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
      take: 5,
    });

    return NextResponse.json({
      total: subscriberCount,
      recent: recentSubscribers,
    });
  } catch (error) {
    console.error('Error fetching subscriber info:', error);
    return NextResponse.json(
      { error: 'Failed to fetch subscriber information' },
      { status: 500 }
    );
  }
}
