export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import { VOCAB } from '@/lib/white-label/constants';
import { z } from 'zod';

const newsletterSchema = z.object({
  email: z.string().email('Valid email is required').max(255),
  source: z.string().max(50).optional().default('footer'),
});

export async function POST(request: NextRequest) {
  try {
    const body = await request.json().catch(() => null);
    if (!body) {
      return NextResponse.json(
        { success: false, error: 'Invalid JSON body' },
        { status: 400 }
      );
    }

    const parsed = newsletterSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json(
        { success: false, error: parsed.error.issues[0]?.message || 'Invalid input' },
        { status: 400 }
      );
    }

    const { email, source } = parsed.data;

    // Check if already subscribed
    const existing = await prisma.newsletterSubscriber.findUnique({
      where: { email: email.toLowerCase().trim() }
    });

    if (existing) {
      if (existing.status === 'unsubscribed') {
        // Resubscribe
        await prisma.newsletterSubscriber.update({
          where: { email: email.toLowerCase().trim() },
          data: {
            status: 'active',
            subscribedAt: new Date(),
            unsubscribedAt: null,
            source
          }
        });
        return NextResponse.json({
          success: true,
          message: `Welcome back! You've been resubscribed to the ${VOCAB.brief}.`
        });
      }
      return NextResponse.json({
        success: true,
        message: 'You\'re already on the list. First Brief drops soon.'
      });
    }

    // Create new subscriber
    await prisma.newsletterSubscriber.create({
      data: {
        email: email.toLowerCase().trim(),
        source,
        status: 'active'
      }
    });

    return NextResponse.json({
      success: true,
      message: `You're in. The ${VOCAB.brief} hits your inbox weekly.`
    });
  } catch (error) {
    console.error('Newsletter subscription error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to subscribe. Please try again.' },
      { status: 500 }
    );
  }
}

export async function GET() {
  try {
    const count = await prisma.newsletterSubscriber.count({
      where: { status: 'active' }
    });
    return NextResponse.json({ subscribers: count });
  } catch (error) {
    console.error('Newsletter count error:', error);
    return NextResponse.json({ subscribers: 0 });
  }
}
