import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { logger } from "@/lib/logger";

export async function POST(request: Request) {
  try {
    const { email } = await request.json();

    if (!email || typeof email !== "string" || !email.includes("@")) {
      return NextResponse.json(
        { error: "Valid email required" },
        { status: 400 }
      );
    }

    const normalized = email.toLowerCase().trim();

    // Upsert — idempotent, no error on duplicate
    await db.waitlistEntry.upsert({
      where: { email: normalized },
      update: {},
      create: { email: normalized },
    });

    logger.info({ action: "waitlist_signup" }, "Waitlist signup");

    return NextResponse.json({ ok: true });
  } catch (err) {
    logger.error({ err, action: "waitlist_signup_error" }, "Waitlist signup failed");
    return NextResponse.json(
      { error: "Something went wrong" },
      { status: 500 }
    );
  }
}

export async function GET() {
  try {
    const count = await db.waitlistEntry.count();
    return NextResponse.json({ count });
  } catch {
    return NextResponse.json({ count: 0 });
  }
}
