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

export async function POST(request: Request) {
  // Complements Payload's own per-account lockout (5 attempts / 10min,
  // see Customers.ts in the Payload repo) with a per-IP layer — that one
  // alone doesn't stop someone spraying single attempts across many
  // different email addresses from the same IP.
  if (!checkRateLimit(`login:${getClientIp(request)}`, { limit: 10, 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 email = typeof body?.email === "string" ? body.email : "";
  const password = typeof body?.password === "string" ? body.password : "";
  if (!email || !password) {
    return NextResponse.json({ ok: false, reason: "Bitte E-Mail und Passwort angeben." }, { status: 400 });
  }

  const result = await loginCustomer({ email, password });
  if (!result.ok) return NextResponse.json(result, { status: 401 });

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