import { NextRequest, NextResponse } from "next/server";
import { db, isDatabaseAvailable } from "@/lib/db";
import { ensureDatabaseInitialized } from "@/lib/db/init";
import { waitlist } from "@/lib/schema/db";
import { newId } from "@/lib/auth/tokens";
import { sanitizeText } from "@/lib/ingest/sanitize";
import { MAX_JSON_BODY_BYTES } from "@/lib/limits";
import { readJsonSized } from "@/lib/http/requestSize";
import { requireCsrf } from "@/lib/auth/csrf";

export const runtime = "nodejs";

export async function POST(req: NextRequest) {
  const csrfBlocked = requireCsrf(req);
  if (csrfBlocked) return csrfBlocked;

  if (!isDatabaseAvailable()) {
    return NextResponse.json({ error: 'Database unavailable' }, { status: 503 });
  }
  await ensureDatabaseInitialized();

  try {
    const parsed = await readJsonSized<{
      email?: string;
      name?: string;
      source?: string;
    }>(req, MAX_JSON_BODY_BYTES);
    if (!parsed.ok) return parsed.response;
    const body = parsed.body ?? {};
    const { email, name, source } = body;

    // Sanitize before the email check: control chars / markup / surrounding
    // whitespace can't be part of a legitimate address, and the value is
    // persisted verbatim afterwards.
    const cleanEmail = sanitizeText(email, 255).toLowerCase();
    if (!cleanEmail) {
      return NextResponse.json({ error: 'Valid email is required' }, { status: 400 });
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(cleanEmail)) {
      return NextResponse.json({ error: 'Invalid email format' }, { status: 400 });
    }

    try {
      await db.insert(waitlist).values({
        id: newId("wl"),
        email: cleanEmail,
        name: name == null ? null : sanitizeText(String(name), 160) || null,
        source: source == null ? null : sanitizeText(String(source), 100) || null
      });
    } catch (e: any) {
      // Ignore unique constraint violation (duplicate email)
      // Usually postgres returns 23505 for unique violation
      if (e.code === '23505' || e.message.includes('unique constraint')) {
        return NextResponse.json({ success: true });
      }
      throw e;
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Waitlist POST error:", error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
