import { NextResponse } from "next/server";
import { checkEmailExists } from "../../../lib/customerAuth";
import { checkRateLimit, getClientIp } from "../../../lib/rateLimit";

// Called on blur from the checkout email field (CheckoutContent.tsx) —
// lets the form switch to login mode as soon as an existing account is
// detected, instead of only after a failed registration attempt. Same
// exposure as the registration-collision case already had (both reveal
// "this email has an account"), so rate-limited the same way rather than
// treated as a new problem.
export async function POST(request: Request) {
  if (!checkRateLimit(`check-email:${getClientIp(request)}`, { limit: 20, windowMs: 15 * 60 * 1000 })) {
    return NextResponse.json({ exists: false }, { status: 429 });
  }

  const body = await request.json().catch(() => null);
  const email = typeof body?.email === "string" ? body.email : "";
  if (!email) return NextResponse.json({ exists: false });

  const exists = await checkEmailExists(email);
  return NextResponse.json({ exists });
}
