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

export async function POST(request: Request) {
  if (!checkRateLimit(`reset-password:${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 token = typeof body?.token === "string" ? body.token : "";
  const password = typeof body?.password === "string" ? body.password : "";
  if (!token || !password || password.length < 8) {
    return NextResponse.json({ ok: false, reason: "Bitte ein neues Passwort (mind. 8 Zeichen) angeben." }, { status: 400 });
  }

  const result = await resetPassword(token, password);
  if (!result.ok) return NextResponse.json(result, { status: 400 });

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