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

export async function POST(request: Request) {
  if (!checkRateLimit(`register:${getClientIp(request)}`, { limit: 5, windowMs: 15 * 60 * 1000 })) {
    return NextResponse.json({ ok: false, reason: "Zu viele Versuche. Bitte in ein paar Minuten erneut probieren." }, { status: 429 });
  }

  const body = await request.json().catch(() => null);
  const { firstName, lastName, email, password } = body ?? {};
  if (
    typeof firstName !== "string" ||
    typeof lastName !== "string" ||
    typeof email !== "string" ||
    typeof password !== "string" ||
    !firstName ||
    !lastName ||
    !email ||
    !password
  ) {
    return NextResponse.json({ ok: false, reason: "Bitte alle Felder ausfüllen." }, { status: 400 });
  }

  const result = await registerCustomer({ firstName, lastName, email, password });
  if (!result.ok) return NextResponse.json(result, { status: 400 });

  await setSessionCookie(result.token);
  return NextResponse.json({ ok: true, customer: result.customer });
}
