import { NextRequest, NextResponse } from 'next/server';
import { jsonError } from '@/lib/auth-helpers';
import { getServiceRoleSupabase } from '@/lib/supabase';

export const dynamic = 'force-dynamic';

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const ALLOWED_LISTS = new Set(['merch', 'ledger-book', 'The Line', 'The Edge', 'The Correlation', 'The System', 'general']);

export async function POST(req: NextRequest) {
  let body: { email?: string; list?: string; honeypot?: string };
  try {
    body = await req.json();
  } catch {
    return jsonError(400, 'Invalid JSON.');
  }

  // Honeypot — silently accept then drop
  if (body.honeypot) return NextResponse.json({ ok: true });

  if (!body.email || !EMAIL_RE.test(body.email)) {
    return jsonError(400, 'Enter a valid email.');
  }
  const list = body.list && ALLOWED_LISTS.has(body.list) ? body.list : 'general';

  const sb = getServiceRoleSupabase();
  if (sb) {
    await sb
      .from('waitlist_signups')
      .insert({ email: body.email.toLowerCase(), list, source: 'web' })
      .select()
      .maybeSingle();
  }

  return NextResponse.json({ ok: true, list });
}
